Re: Declaring local variables inside loop



Jacob <jacob@xxxxxxxxx> wrote:
Hendrik Maryns wrote:

I do some looping like this:

FunctionInputTuple tupleWithSecond;
while (tupleStates.contains(first)) {
tupleWithSecond = FunctionInputTuple.getInstance(
tuple.getSymbol(), tupleStates);
// do some computation, replace ?first? in the list
equivalent &= equivalence.equivalent(firstValue,
secondValue);
}

Now my question is: does it matter that I declare tupleWithSecond
outside the loop? I have the impression that if I leave the first
line out and instead add ?FunctionInputTuple? before the third line,
that a new pointer space is created on the stack for each loop. Or
is the compiler smart enough to see this and optimise it away?

In general you should limit the scope of names, so
declaring the variable inside the loop is preferable.

I don't know the technical details and the two cases
*may* in principle differ performance wise (I don't
think they do), but this whould be what is commonly
known as "premature optimization" and should be avoided
anyway.

Seconding that: the JVM is very likely to optimize this situation. I definitively would prefer to limit the scope as much as possible to avoid errors from accidetally reusing the same value and enabling proper data flow analysis of the compiler.

Kind regards

robert

.



Relevant Pages

  • Re: Declaring local variables inside loop
    ... FunctionInputTuple tupleWithSecond; ... new pointer space is created on the stack for each loop. ... known as "premature optimization" and should be avoided ...
    (comp.lang.java.programmer)
  • Re: Declaring local variables inside loop
    ... FunctionInputTuple tupleWithSecond; ... new pointer space is created on the stack for each loop. ... for variable1 and 2. ...
    (comp.lang.java.programmer)
  • Declaring local variables inside loop
    ... You need GnuPG to verify this message ... FunctionInputTuple tupleWithSecond; ... new pointer space is created on the stack for each loop. ...
    (comp.lang.java.programmer)