Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it more efficient to declare a variable inside a loop, or just to reassign it?

While writing loops I often get confused with which one I should choose. For example,

int sum;
for(int i=0; i<10; i++)
{
   sum=0;
   ...
   ....
}

Or

for(int i=0; i<10; i++)
{
   int sum=0;
   ...
   ....
}

Say, the variable is only required in this loop. There is no need of it in the later part of the program. I need the value of the variable sum to be 0 at the beginning of the loop. Which one is the better practice? Re-initializing a variable at the start of the loop or re-declaring it? Which one is more efficient?

like image 966
anirban.at.web Avatar asked Oct 15 '14 05:10

anirban.at.web


People also ask

Is it good to declare variable in loop?

It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope. What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs.

Should I declare variable inside loop or outside?

If the variable is declared outside the loop, then it has the global scope as it can be used through-out the function and inside of the loop too. If the variable is declared inside the loop, then the scope is only valid inside the loop and if used outside the loop will give an error.

What happens if we declare a variable inside loop?

If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.

Where is the best place to declare variables?

The recommended practice is to put the declaration as close as possible to the first place where the variable is used. This also minimizes the scope. From Steve McConnell's "Code Complete" book: Ideally, declare and define each variable close to where it's first used.


1 Answers

If you declare a variable outside of the loop and not use it past the loop, the compiler will move the declaration inside the loop.

That means there is no reason to compare efficiency here, since you end up with the same exact code that the JVM will run for the two approaches.

So the following code:

int sum;
for(int i=0; i<10; i++)
{
   sum=0;
}

... becomes this after compilation:

for(int i = 0; i < 10; i++)
{
    int sum = 0;
}
like image 82
Voicu Avatar answered Nov 07 '22 19:11

Voicu