When I write a simple for loop like this
for (int i = 0; i < myList.size(); i++){}
in Java, C and C++, does it reevaluates myList.size() in each iteration or just for once at the beginning of the loop? If it reevaluates, does preevaluating size, i.e.,
int n = myList.size();
for (int i = 0; i < n; i++){}
gives us something significant in terms of performance?
For Java:
for (int i=0; i<myList.size(); i++){}
The condition is evaluated during each loop iteration; so there is a slight performance gain by moving that call to size()
in front of the loop.
But in Java you should prefer the for-each
for (Whatever thingy : list)
notation anyway (where possible).
You can read about in the Java language spec, chapter 14.14.1.
In both C and C++, the controlling expression is evaluated on each iteration of the loop.
From section 6.8.5.3 of the C standard:
The statement
for (clause-1; expression-2; expression-3) statement
behaves as follows: The expression
expression-2
is the controlling expression that is evaluated before each execution of the loop body. The expressionexpression-3
is evaluated as a void expression after each execution of the loop body. Ifclause-1
is a declaration, the scope of any identifiers it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. Ifclause-1
is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.
Section 6.5.3 of the C++ standard contains similar verbiage.
So if your controlling expression involves a function call or some other potentially expensive computation that won't change in the loop body, you should evaluate it beforehand, store it in a variable, then use that variable in the controlling expression.
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