Recently I found myself writing for loops that use Iterators a little differently. I used to write loops like this:
Iterator fooIter = bar.getFoos();
Foo foo;
while( fooIter.hasNext() ) {
foo = (Foo)fooIter.next();
[...]
}
And now I've moved to this:
for( Iterator fooIter = bar.getFoos().iterator(); fooIter.hasNext(); ) {
Foo foo = (Foo)fooIter.next();
[...]
}
Its nice and tight, but still readable. But I've always wondered about instantiating a temporary reference inside a loop. I wrote this code to try to tell what effect it has on performance.
I wrote this code:
public class Foo {
private static int SIZE = 999999;
public static void main( String args[] ) {
String strArray[] = new String[SIZE];
for( int i = 0; i < SIZE; i++ ) {
strArray[i] = Long.toString( System.currentTimeMillis() );
}
int count = 0;
long timer = System.currentTimeMillis();
for( int i = 0; i < SIZE; i++ ) {
String str = strArray[i];
count += str.length(); // make sure the loop does something;
}
System.out.println("timer: " + (System.currentTimeMillis() - timer) );
timer = System.currentTimeMillis();
String str;
for( int i = 0; i < SIZE; i++ ) {
str = strArray[i];
count += str.length(); // make sure the loop does something;
}
System.out.println("timer: " + (System.currentTimeMillis() - timer) );
System.out.println("count: " + count );
}
}
Well, the output wasn't too suprising, exactly the same times. I hope my test aren't completely bogus. I'd feel better if I had a definite confirmation of performance either way.
Until I can use Java 1.5 on a project I'll probably stick with this...
<< Home