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?
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With