gpt4 book ai didi

java - 数组循环性能中哪一个更快?

转载 作者:行者123 更新时间:2023-12-01 18:17:21 26 4
gpt4 key购买 nike

我是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 循环?

最佳答案

在现实生活中,使用 foreach 还是 for 循环并不重要。性能差异几乎不明显。如果需要当前索引,则执行 for 循环,如果不需要,则使用 foreach。至于长度,它只是一个属性,因为它是一个数组,所以它在数组初始化时设置并且永远不会改变。读取特性的值(value)几乎不需要任何时间。因此,为了便于阅读,将其放入 for 循环的条件中

关于java - 数组循环性能中哪一个更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com