What are the advantages of using one integer for multiple loops?

As the name suggests, what are the benefits of this:

int i;

for (i = 0; i < 4; i++){
    <do stuff>
}

for (i = 0; i < 7; i++){
    <do other stuff>
}

      

instead of this:

for (int i = 0; i < 4; i++){
    <do stuff>
}

for (int i = 0; i < 7; i++){
    <do other stuff>
}

      

In other words, is there any advantage to not declaring a different variable for each loop?

I would assume they require less memory to store them, but they will both be disposed of at the end of the method, so why does it matter? (Or the GC will just get rid of them)

+3


source to share


4 answers


Both solutions will almost certainly take exactly the same amount of memory, and there will be no heap memory involved (GC doesn't matter).

Even at the level javac

it can be easily detected when a local variable in the second case goes out of scope (outside the loop for

), and the space used for it can be reused for another loop.



At run time, the variable will likely be assigned to a register and, given many of the details of the actual JVM code and implementation, the loop will be unwrapped or transformed in other ways, making it impossible to even understand the meaning of the "memory usage" concept of that variable.

+5


source


Just remember that lazy programmers sometimes use a loop variable to determine if the loop terminated correctly, for example:

int i;
for (i = 0; i < 7; i++){
    if (someRandomCondition)
      break;
}

if (i < 7)
 ... Oops, we exited early

      



This is obviously bad practice - it would be better to keep this early exit status elsewhere, so refactoring may be necessary if you remove scope.

+4


source


There are no advantages or disadvantages associated with it ... It is based on the need for this variable If you need this variable everywhere in the class, then it must be declared outside of methods or loops. But if it's created just to use the loop, then there is no need to declare it first, and they will have much the same effect in memory.

0


source


I think you have the right idea. The only difference is that the variable becomes garbage.

In the first example, the integer wil becomes garbage when the parent method completes. In the second example, integers become garbage when each of the for loops ends.

If the language you are using has automatic garbage collection (Java), then declaring an int with a for loop may result in memmory being preserved. Later in the same parent method, the int will be cleared, and you don't have to worry about that integer being allocated until the method completes.

0


source







All Articles