Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does declaring a variable many times slow down the execution?

Tags:

java

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.

like image 619
Beppi's Avatar asked Jul 18 '13 16:07

Beppi's


3 Answers

Declaring a variable has no impact on performance. Once the code is compiled the JIT is smart enough to pre-assign local variables.

Technically, limiting the scope of a variable can improve performance as it doesn't have to keep the variable after it is no longer needed, but I suspect the JIT is smart enough to work that out as well.

like image 136
Peter Lawrey Avatar answered Sep 28 '22 05:09

Peter Lawrey


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.

like image 40
Chandima Prematillake Avatar answered Sep 28 '22 04:09

Chandima Prematillake


Declaring a variable influences compile time, not run time. The space the local variable is going to occupy on the stack is allocated at compile time, so run-time is not going to get influenced.

What's going to get influenced is readability: generally, it is best to declare your variables close to places where they get used, and keep them in as tight a scope as your program allows. In this sense, your first code snippet is best.

The only reason to go with snippets 2 or 3 is when you need the value of variables i or j after the loop has finished, for example, to find out when a break statement has been executed. It is not possible to tell from your examples if this is the case or not.

like image 40
Sergey Kalinichenko Avatar answered Sep 28 '22 04:09

Sergey Kalinichenko