Reputation: 359
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?
Upvotes: 9
Views: 2756
Reputation: 666
Re initializing it within the loop will set the sum value to zero every time you start the loop, no need to re-declare. The answer is both have same efficiency.
Upvotes: 0
Reputation: 17860
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;
}
Upvotes: 10
Reputation: 1346
This leads us to concentrate on performance and optimization
of code in looping concepts.
From a maintenance perspective, second case is better. Declare and initialize variables in the same place, in the narrowest scope
possible. Don't leave a gaping hole between the declaration
and the initialization
.The scope of local variables should always be the smallest possible.See the link
Declaring variables inside or outside of a loop
Upvotes: 1