Lesson learned

`
String message, line;

for (;:wink: {
line = in.readLine();
message += line;
}
`

Time taken to download a 1500 line email: 13 secs
Oh dear. Java is so slow! (Reads API…) What’s this StringBuffer all about then?

`
StringBuffer message;
String line;

for (;:wink: {
line = in.readLine();
message.append(line);
}
`

Time taken to download a 1500 line email: 50ms

Hurrah! Java is fast!

I wish all optimisations were as easy as this!

I thought the compiler now handled all string concatenation with SB’s anyway? And in the trivial analysis of that code there would be no obvious need to through away the intermediate SB between calls. Do you get different behaviour with server compared to client?

i’ll bet that if you decompile

 for (;;) {
    line = in.readLine();
    message += line;
} 

you’ll see something like that:

String message;
 for (;;) {
    line = in.readLine();
    StringBuffer sb = new StringBuffer( message );
    sb.append( line );
    message = sb.toSTring();
} 

I think Pepe is correct… all string concatenation is done with SBs, but there is no optimization to keep the same SB across multiple statements, which is essentially what the loop above is all about.

Indeed. For that reason findbugs has a pattern for detecting that kind of stuff.

Findbugs?
Ok, that’ll be useful then ;D

[quote]Findbugs?
Ok, that’ll be useful then ;D
[/quote]
If you were going to post that you googled you might as well have posted the link so I didn’t have to take my hand off the mouse :slight_smile:

http://findbugs.sourceforge.net/

[quote] If you were going to post that you googled you might as well have posted the link so I didn’t have to take my hand off the mouse
[/quote]
Sorry!

I really must check out some more Java stuff on Sourceforge, I’ll bet there is a ton of stuff that I’m missing out on.

Yeah… I just installed the FindBugs plugin for Eclipse. It found a few things in my project that needed fixing.

Java 5.0 has a StringBuilder class which is the same as StringBuffer, but isn’t synchronized. So when you start using 5.0 perhaps you’ll want to swtich to the new class.

I have done some experiments with StringBuilder under server hotspot and I was not able to create any microbenchmark where it was noticeably faster. For me, it looks like hotspot is able to determine that this object is local and does not need synchronization ?? Situation will probably look different if you will pass StringBuffer/StringBuilder between methods.