Reputation: 117
Suppose there is a loop in which there is an integer variable named counter
that needs to be reset to 0 for every iteration. Which of the two versions would be more efficient?
Version-1:
for (int i = 0; i < 10; i++) {
int counter = 0;
if (something()) counter++;
}
Version-2:
int counter;
for (int i = 0; i < 10; i++) {
counter = 0;
if (something()) counter++;
}
In the first version, the scope of the counter variable is within the for loop and it's reallocated in memory for every iteration. In the second case, it is just overwritten on a single memory location throughout the program. I think the second version is more efficient but is the efficiency negligible or considerable or is it the other way around?
Upvotes: 0
Views: 75
Reputation: 97168
In the first version, counter will not be reallocated in memory on every iteration. It's a variable of a primitive type (int), so most compilers will store it on the stack. There is no reason to use a different stack location for different iterations on the loop, so it will be stored in the same location, just like in the second version.
(This assumes that the compiler does not elide the counter
variable entirely, because you're not using its value anywhere.)
Upvotes: 1