anirban.at.web
anirban.at.web

Reputation: 359

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?

Upvotes: 9

Views: 2756

Answers (3)

SanyTiger
SanyTiger

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

Voicu
Voicu

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

Anbu.Sankar
Anbu.Sankar

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

Related Questions