哪一个阵列循环性能更快?

时间:2015-03-03 22:21:20

标签: java arrays loops for-loop benchmarking

我是新手Java学习者。我试图理解如何在性能和可读性方面编写高效的代码。在这一点上,阵列对我来说是一个难题。下面是六个原始测试。他们的前三个和后三个几乎同样回归。请解释一下发生了什么。

String s= "";
int[] Array1=new int[100000];
Long startingTime=System.nanoTime();
for (int i = 0; i < Array1.length; i++) {
    s+=i;
}
System.out.println("time : " + (System.nanoTime()-startingTime));

String s= "";
int length=100000;
Long startingTime=System.nanoTime();
for (int i = 0; i < length; i++) {
    s+=i;
}
System.out.println("time : " + (System.nanoTime()-startingTime));

String s= "";
int length1=50000;
int length2=50000;
Long startingTime=System.nanoTime();
for (int i = 0; i < length1+length2; i++) {
    s+=i;
}
System.out.println("time : " + (System.nanoTime()-startingTime));

public class Test3Length {
static class Foo {
int mSplat = 0;
}
public static void main(String[] args) {
int twentyMillions = 20000000;
Foo[] mArray = new Foo[twentyMillions];
for (int i = 0; i < mArray.length; i++) {
    mArray[i] = new Foo();
}
int sum = 0;
Long startingTime = System.nanoTime();
for (int i = 0; i < mArray.length; ++i) {
    sum += mArray[i].mSplat;
}
System.out.println("time : " + (System.nanoTime() - startingTime));
}
}

public class Test4Length {
static class Foo {
int mSplat = 0;
}
public static void main(String[] args) {
int twentyMillions = 20000000;
Foo[] mArray = new Foo[twentyMillions];
for (int i = 0; i < mArray.length; i++) {
    mArray[i] = new Foo();
}
int sum = 0;
Long startingTime = System.nanoTime();
for (int i = 0; i < twentyMillions; ++i) {
    sum += mArray[i].mSplat;
}
System.out.println("time : " + (System.nanoTime() - startingTime));
}
}

public class Test5Length {
static class Foo {
int mSplat = 0;
}
public static void main(String[] args) {
int twentyMillions = 20000000;
Foo[] mArray = new Foo[twentyMillions];
for (int i = 0; i < mArray.length; i++) {
    mArray[i] = new Foo();
}
int sum = 0;
Long startingTime = System.nanoTime();
for (Foo a : mArray) {
    sum += a.mSplat;
}
System.out.println("time : " + (System.nanoTime() - startingTime));
}
}

第一个问题,我更愿意在for循环条件中使用int length而不是array.length吗?

第二个问题,除非数组是集合,否则我更喜欢foreach循环而不是for循环?

2 个答案:

答案 0 :(得分:3)

在现实生活中,使用foreach或for循环并不重要。性能差异几乎不可察觉。如果你需要当前索引然后执行for循环,如果没有那么请使用foreach。至于长度,它只是一个属性,因为它是一个数组,它在数组初始化时设置,永不改变。读取房产的价值几乎没有时间。因此,为了便于阅读,请将其置于循环条件

之内

答案 1 :(得分:1)

  

第一个问题,我更愿意在for循环条件中使用int length而不是array.length吗?

字面意思没有区别。 array.length是一个不变量,因此JIT只会访问它一次,使其值在性能方面与局部变量相同。

  

第二个问题,除非数组是集合,否则我更喜欢foreach循环而不是for循环?

当你循环的对象是一个数组时,foreach循环的转换与for循环相同,所以没有任何区别。

然而,总而言之,我应该说你似乎专注于错误的事情。在前三个测试中,几乎所有的运行时间都可能用在s+=i表达式上,因为每个评估都会创建一个新的String,以便向其添加i。通过使用StringBuilder而不是尝试循环结构的不同变体,您可能会看到更大规模的加速。