When you declare a loop variable in a loop, it is very narrow. The compiler can store it in the register all the time, so it does not get memory bindings even once.
When you declare a loop variable as an instance variable, the compiler does not have that flexibility. It should keep the variable in memory if some of your methods want to examine its state. For example, if you do this in your first code example
void method2() { for(i=0; i<B; ++i) { method3(); } } void method3() { printf("%d\n", i); }
the value of i in method3 should change as the loop advances. The compiler is not able to transfer all its side effects to memory. Moreover, he cannot assume that i remained the same when you return from method3 , which will further increase the number of memory accesses.
Working with updates in memory requires a lot more CPU cycles than performing updates for register-based variables. This is why it is always recommended to keep loop variables in the range up to the loop level.
dasblinkenlight
source share