在我的程序中,我有以下类(class):
private static class Node
{
// True if '1', false otherwise (i.e. '0')
public final boolean isDigitOne;
// The number represented in the tree modulo the input number
public final int val;
// The parent node in the tree
public final Node parent;
public Node(boolean isDigitOne, int val, Node parent)
{
this.isDigitOne = isDigitOne;
this.val = val;
this.parent = parent;
}
}
我用另一个类的方法中的两个以下数组替换了该类。
boolean[] product0 = new boolean[num];
int[] product1 = new int[num];
程序的其余部分非常相似,类实现在需要时创建一个对象,而数组实现在执行开始时分配所需的最大内存。
我测量了这两种情况的运行时间。
我注意到对于较小的num
值,执行时间几乎相同。但对于更大的值,数组实现运行得更快。
比较如下:
我的问题是为什么数组实现运行得更快?
类实现可在以下链接中找到,作为“答案 3” How to find the smallest number with just 0 and 1 which is divided by a given number?
最佳答案
其中很大一部分原因在于数据在内存中的位置。对象数组并不直接将数据彼此相邻地存储在内存中,而是存储对数据在内存中存储位置的引用。这意味着在访问数组的位置并从数组中获取数据后,系统必须从数组值所指向的内存位置中获取数据。然而,原始数据数组将数据直接存储在数组中。这意味着系统只需执行一次查找即可访问数组,而不是执行两次查找即可访问数组,然后访问对象。系统通常运行速度非常快,对于较小的数据量来说,这一点并不明显,但当数据量增加时,它就会变得明显。
关于java - 为什么在java中用一些数组(原始数据类型)替换对象(类)会显着减少运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59937597/