Re: Microoptimization - variables inside or out of the loop block?
Ivan Voras wrote:
In other words, does variable declaration inside a loop block result in
extra processing per loop iteration that wouldn't be there if it's
declared only once, outside the block?
Eric Sosman <Eric.Sos...@sun.com> wrote:
The effect, if any, is probably small enough to be difficult
to measure. At a guess (and without having made any of those
difficult measurements), I'd imagine that the second form might
be very slightly slower: By extending the scope of `o' past the
end of the loop it might force Java to use one more stack slot
than it would have otherwise, and it might prevent or delay the
garbage collection of the final LargeObject.
I'd recommend against letting concerns of this kind drive
your implementation decisions.
+1
Properly, the determination of scope is not driven by urban myths
about micro-optimization but by the algorithmic logic of where the
variable should be accessible.
Promoting the scope of a variable outside of a loop where it should be
inside is stupid.
The bytecode analysis (per Stefan Ram) tells only a small part of the
story, and virtually none of the optimization chapter of that story.
Optimization happens in the JVM, in the interpretation of the bytecode
and possible compilation to native code. The JVM is free to
enregister variables, perhaps even elide object creation entirely if
the circumstances are right. Foolish hand-crafted "optimizations" are
more likely to defeat run-time optimization than to help it.
--
Lew