Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a for loop re-evaluate the functions in its body in each iteration?

Tags:

java

c++

c

for-loop

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?

like image 648
SpiderRico Avatar asked Dec 01 '22 15:12

SpiderRico


2 Answers

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.

like image 200
GhostCat Avatar answered May 17 '23 13:05

GhostCat


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 expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-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. If clause-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.

like image 37
dbush Avatar answered May 17 '23 12:05

dbush