Fred,
I thought this was an interesting question, so I did some research which included:
- Reading http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/
- Looking at the Bytecode for methods which declared variables outside
and inside loops.
According to the referenced web site and confirmed by my method/Bytecode
experimentation:
- The total space required for a method's local variables is determined
at compile time. It doesn't matter where the variables are declared
in the method.
Only one memory "slot" is assigned for a variable, even if it's
declared in a loop.
- Declaration statements for local variables don't result in any
Bytecode instructions unless the variable is also initialized.
All memory for local variables is allocated prior
to the execution of a method body.
I compared code that declares (without initializing) the variable outside the
loop with code that declares it inside the loop. The resulting Bytecode is
essentially identical and has the same time and memory requirements.
If the variable is declared and initialized outside the loop, slightly more code
is required for the initialization which would slightly increase time and memory
requirements.
So, it all comes down to readability. I believe that the code is most readable
when local variables are declared closest to their first use (inside the loop).
I believe that most Java programmers would agree, but it wouldn't be hard to
find C++ programmers with the opposite view.
> I gave students a bit of code involving
> a local variable that was repeatedly declared and assigned to an object
> inside of a loop. The student asked me whether it would be more efficient
> to declare the variable outside of the loop and only reassign it inside the
> loop. Would it be more efficient in time, memory, or both?
>
> 1 public double getTotal()
> 2 {
> 3 double total = 0;
> 4 int i = 0;
> 5 while (i < money.size())
> 6 {
> 7 Coin tempCoin = money.get(i);
> 8 total += tempCoin.getValue();
> 9 i++;
> 10 }
> 11 return total;
> 12 }
--
Robert Glen Martin
School for the Talented and Gifted