Tamby Kojak
Tamby Kojak

Reputation: 2159

Which for loop header performs better?

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?

Upvotes: 0

Views: 3641

Answers (3)

M A
M A

Reputation: 72854

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.

Upvotes: 1

Val
Val

Reputation: 11107

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.

Upvotes: 2

Sumedh
Sumedh

Reputation: 404

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.

Upvotes: 2

Related Questions