Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Difference between for loop terminating expression

I'm just curious: Is there a difference on speed and performance between this two loops implementation? Assume that size() method returns the length of the array,collection, or object that handles a group of elements (actually it's from XOM api).

Implementation 1:

int size = someArray.size();
for (int i = 0; i < size; i++) {
    // do stuff here
}

Implementation 2:

for (int i = 0; i < someArray.size(); i++) {
    // do stuff here
}
like image 952
John Bautista Avatar asked Feb 26 '11 10:02

John Bautista


People also ask

What is the difference between i ++ and ++ i in for loop?

Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated. To answer the actual question, however, they're essentially identical within the context of typical for loop usage.

What is a for loop initialization?

The initialization is an expression that initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false , the loop terminates.

What do you think is the advantage of using a Java looping structure in a program?

Loops in java are used to execute the block of statement repeatedly until the condition is true. By using the loop, we can execute the code several times or until it is satisfying the condition. Loops are very useful when a programmer wants to execute a statement or block of statement multiple times.


2 Answers

From a performance point of view, there is little difference. This is because a loop can be optimized so that the size() lookup is inlined, resulting in very little performance difference.

The main difference is if the size changes while looping. The first case will try to iterate a fixed number of times. In the second case, the number of iterations will depend on the final size().

like image 113
Peter Lawrey Avatar answered Oct 12 '22 12:10

Peter Lawrey


The 1st snippet is bound to execute faster since it calls size() once only. The 2nd snippet calls size() N times. Depending on the impl. it might pose significant penalty, esp. if the compiler finds hard to inline the method and/or the size() method doesn't just return non-volatile variable, etc.

I'd have rewritten it like for(int i=0, s=someCollection.size(); i<s; i++)

Note: arrays don't have size() method.

like image 33
bestsss Avatar answered Oct 12 '22 11:10

bestsss