下面的两个代码段在性能方面有什么区别吗?
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语句,但是没有一种会多次调用该方法。
简单测试表明该方法仅被调用一次
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循环外使用该数组。
编辑
您让我好奇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循环重构为标准循环!它还进一步证明,实际上,在编译器通过它们之后,它们是完全相同的。