Friday, April 29, 2005

Bytecode of method variables

Having installed the Bytecode Outline Eclipse plugin, and read the online instruction reference it would appear that the following two code extracts produce similar bytecode:

for (final java.util.Iterator iter = categories.iterator(); iter.hasNext();) {
final String s = (String)iter.next();
}

String s=null;
for (final java.util.Iterator iter = categories.iterator(); iter.hasNext();) {
s = (String)iter.next();
}

ALOAD appears to be used in both cases, implying that there is no performance advantage gained by moving the String outside the for loop

2 Comments:

At 9:11 am, Anonymous Anonymous said...

I don't think such a thing would ever noticeably slow your application down anyway. But, it's good to know that you can trust javac (and the JVM) to do what's right.

 
At 4:04 am, Anonymous Anonymous said...

Any compiler/optimizer worth its salt will never allow placement of a variable declaration to affect the generated machine/byte code.

The final on the iterator is useless. Optimizers do data flow analysis and can see where variables are modified. In this case, the optimizer can see that the iterator variable is only modified once.

If you're really interested in code optimizations read the "dragon" book on compilers (so-called because of the dragon on the cover).

 

Post a Comment

<< Home