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
}
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.
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.
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.
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With