• Post Reply Bookmark Topic Watch Topic
  • New Topic

'+' performing faster than StringBuffer.append() ???

 
Rajagopal Manohar
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Programming in Java for over 1-1/2 years now, I have picked up this impression that

String x = y+z; will be slower than a StringBuffer.append. I dont know why but it was a strong conviction I had

but today for the first time when I had to proove this to someone and I ran a BenchMark test where I did something like

for(20000 times){
String s = a+"~"+b+"~"+c+...4 to 5 more strings
clear s
}

and

for(20000 times){
stringbuffer.append(a);
stringbuffer.append("~");
.
.
.
create a new String from buffer
}

I found the latter to be much slower

Even more surprise though string.concat() performed better than the buffer it was still a tad slower than the one that used "+"

So is using "+" to append string the fastest way after all
-Rajagopal
[ January 06, 2006: Message edited by: Rajagopal Manohar ]
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First and foremost, you should be aware that due to the HotSpot JIT compiler/optimizer, microbenchmarks like your examples can be very misleading. Depending on how you declared your variables you are concatenating together with +, the compiler may have just gone ahead and created a single literal for that expression. That would make "+" perform much faster because it isn't doing any work at run time. Have a look at the Java Tuning White Paper that Michael Ernest linked to yesterday.
Second, the code:

is a convenience expression for something like:

They both end up as the same bytecode. Where it makes sense to write StringBuffer.append()'s rather than using + is when you are constructing a long string from several variables and using + would result in creating lots of intermediate StringBuffer instances under the covers.
[ January 06, 2006: Message edited by: Joe Ess ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because Jim's not around this morning ( ) I will have to add that Java 5 now uses StringBuilder to implement '+' rather than StringBuffer; this new class is somewhat faster than the old because it's not synchronized.

But in any case, Joe's right: microbenchmarks are tricky and unreliable things. First, you should use "javap -c" to decompile your program and look at the bytecode: you may be surprised by what you see. And second, even if you see that the first loop contains some bytecode (a compiler could lift the assignment out of the loop, or optimize it away altogether!) HotSpot is even smarter than javac, and so the same optimizations may be done at runtime.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!