Which for loop header performs better?

耗尽温柔 提交于 2019-12-25 16:27:32

问题


I see the following a lot in the Android documentation:

int n = getCount();

for (int i = 0; i < n; i ++) {
    // do somthing
}

But I'm used to seeing and doing:

for (int i = 0; i < getCount(); i ++) {
    // do somthing
}

I'm curious if one is more efficient than the other? What is exactly happening in these two scenarios? When you call getCount() in the second way, does the computer have to allocate another variable? Or is it simply a matter of code cleanliness or preference?


回答1:


This is what the javac compiler of JDK1.6.0_21 generates for the two cases:

First case:

int n = getCount();

for (int i = 0; i < n; i ++) {
    // do something
}

Compiled bytecode:

invokestatic example/Test/getCount()I
istore_1
iconst_0
istore_2
goto 10
... // whatever code in the loop body
iinc 2 1
iload_2
iload_1
if_icmplt 6
return

Second case:

for (int i = 0; i < getCount(); i ++) {
    // do something
}

Compiled bytecode:

iconst_0
istore_1
goto 8
... // whatever code in the loop body
iinc 1 1
iload_1
invokestatic example/Test/getCount()I
if_icmplt 4
return

It may seem that the resulting code is different, but depending on getCount(), the runtime may optimize the execution. Generally speaking, the first code seems more efficient, especially when getCount() does some complex operations to return its value.




回答2:


The First one is more efficient than the other.

In first scenario, you're calling getCount just once,while in second scenario you are calling getCount for every condition check,which increase the execution time of loop.




回答3:


The issue is not performance, thought second can be slower because

public class stuff {
    static int getCount() {
        System.out.println("get count");
        return 5;
    }
    public static void main(String[] args) {
        for (int i = 0; i < getCount(); i ++) {
            System.out.println("loop " + i);
        }
    }

}

has output

get count
loop 0
get count
loop 1
get count
loop 2
get count
loop 3
get count
loop 4
get count

Do you see that getCount in the loop is executed multiple times? Why is it not an issue? How can you compare performances of different things? If behaviour does not matter, you can be happy comparing nop with themostcomplexComputionInThe world.



来源:https://stackoverflow.com/questions/28506401/which-for-loop-header-performs-better

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!