Tuesday, December 18, 2007

N&N in Eclipse 3.4M4: StringBuffer "Optimization"

Another one for the futile/harmful optimization awards: The New & Noteworthy page for Eclipse 3.4M4 says:

The new 'Convert to StringBuffer' quick assist (Ctrl+1) transforms string concatenations into more efficient, albeit less compact, code using an explicit StringBuffer:

Hello? Since when is using StringBuffer more efficient than using String concatenation? Answer: It was upto Java 1.3 (or maybe 1.2; I'm too lazy to look it up right now).

With Java 1.4, the compiler used StringBuffer as well, so this optimization doesn't buy anything but makes the code harder to read.

Worse, with Java 1.5, the compiler generates more optimal code by using StringBuilder instead of StringBuffer. The builder is not synchronized; since string concatenation doesn't suffer from threading issues, this is safe and faster!

And the morale: If you optimize something, make sure you don't rely on some myth about X being faster than Y.

PS: Of course, there is already a bug tracking this.

No comments: