Possible Duplicate:
Declaring variables inside or outside of a loop
Please consider these 2 samples of Java code:
// 1st sample
for (Item item : items) {
Foo foo = item.getFoo();
int bar = item.getBar();
// do smth with foo and bar
}
// 2nd sample
Foo foo;
int bar;
for (Item item : items) {
foo = item.getFoo();
bar = item.getBar();
// do smth with foo and bar
}
Is there any difference in performance/memory consumption between the samples? If it is, then does it depend on type of a handle (an Object vs. a primitive)?
It makes a difference in terms of the byte code generated but no difference in terms of performance.
What is far more important is making the code as simple, self contained and maintainable as possible. For this reason I would prefer the first example.
BTW: Simpler code is often optimised better because its easier for the JIT to optimise as much as it can. Confusing code will also confuse the JIT and it will prevent optimisations being used.
If you use ASMifierClassVisitor which dumps the raw byte code in a readable form (and can be turned back into the original byte code) You will see that
javapglosses over some of the details which are not so important.If I compare (on the left below) at 951 bytes long.
with (on the right below) and 935 bytes long.
You can see at the very least the debug line numbers must be different, but also some of the code is different as well as the local variables defined in a different order and given different allocation numbers.
You can
right click=>View Imageto see the image better.