Does declaring a variable many times slow down the execution?
java
Solution
Once code is optimized by the compiler there should be no difference.
If you are running under debug mode where by default optimization is turned off, if you declare the variable inside the loop scope, it is less efficient than declaring the variable outside the loop scope.
In this case for every iteration of the loop, the code will create space for the variable on stack and after the iteration it will be discarded. This is slightly inefficient.
But for the loop variable (i) where you declare it before the for loop or inside doesn't matter because it will be allocated on stack only once.
Therefore to conclude in debug mode, both 2 and 3 performs better than 1. And in release mode all 3 will be the same.
Problem
Between these three sources, is there a difference in terms of efficency? ``` for (int i=0; i<N; i++) int j = whatever(); ``` and ``` int j; for (int i=0; i<N; i++) j = whatever(); ``` and ``` int i, j; for (i=0; i<N; i++) j = whatever(); ``` Thanks. PS: obviously my question is not referred to the scope of the variable but only on the efficency of the loop, expecially in the first two cases, where the variable j is declared one vs. N times.