下面的两个代码片段在性能方面有什么不同吗?
for(String project : auth.getProjects()) {
// Do something with 'project'
}
和
String[] projects = auth.getProjects();
for(String project : projects) {
// Do something with 'project'
}
对我来说,我认为第二个更好,但更长。第一个较短,但我不确定它是否更快。我不确定,但对我来说似乎每次迭代循环时,都会调用 auth.getProjects
。不是吗?
最佳答案
编辑:@StephenC是的,JLS 是一个更好的地方,可以为这种性质的事情找到答案。这是一个link to the enhanced for loop在语言规范中。在那里你会发现它生成了几种不同类型的 for 语句,但没有一个会调用该方法超过 1 次。
简单测试,该方法只调用一次
public class TestA {
public String [] theStrings;
public TestA() {
theStrings = new String[] {"one","two", "three"};
for(String string : getTheStrings()) {
System.out.println(string);
}
}
public String[] getTheStrings() {
System.out.println("get the strings");
return theStrings;
}
public static void main(String [] args) {
new TestA();
}
}
输出:
get the strings
one
two
three
所以本质上它们是同一回事。如果您想在 for 循环之外使用数组,则 2nd 的唯一好处可能是。
编辑
你让我很好奇 java 编译器是如何处理这个的,所以我使用上面的代码反编译了类文件,结果是这样的
public class TestA
{
public TestA()
{
String as[];
int j = (as = getTheStrings()).length;
for(int i = 0; i < j; i++)
{
String string = as[i];
System.out.println(string);
}
}
public String[] getTheStrings()
{
System.out.println("get the strings");
return theStrings;
}
public static void main(String args[])
{
new TestA();
}
public String theStrings[] = {
"one", "two", "three"
};
}
如您所见,编译器只是将您的 for 循环重组为标准循环!也进一步证明,实际上编译器通过后它们是一模一样的。
关于java - 这两个循环之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23452537/