• Post Reply Bookmark Topic Watch Topic
  • New Topic

Stringbuffer is not always preferable over String  RSS feed

 
Sadanand Murthy
Ranch Hand
Posts: 382
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've seen some questions on using Stringbuffer instead of String objects when concatenating strings is involved. The following article points out that using String1 + String2 ... is more effecient is certain instances than using a StringBufferObject and do a bunch of .appends.
Stringbuffer Myth
[ February 05, 2004: Message edited by: Sadanand Murthy ]
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think this is what they were saying. Their point is that

gets converted to

in the compiler before the bytecode gets generated. That is: the .java file contains some code that would perform poorly in older java versions, the compiler recognises an improvement for this general case and outputs the more efficient bytecode.
...is more effecient is certain instances than using a StringBufferObject...
So this statement is not true. What you end up with is the same bytecode as if you had used a StringBUffer yourself. It isn't more efficient code, it's the same code.
When the original author goes on to say they fail to see the benefit of StringBuffers, it has a huge advantage when the concatenation doesn't all occur at once ie

In the above case the compiler is unable to perform any optimisation substitute so the 'bad' version would suffer the classic String concatenation performance hit, but the 'good' version would not.
Dave
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If all the parts of an expression are compile-time constants concatenated with +, the whole expression is a compile-time constant. (See detailed rules.) In this context an expresison can h If you've got a compile-time constant expression, the whole thing can be evaluated at compile time rather than run time. Which is indeed more efficient. So

is faster than

Of course, this effect is still trivial in most cases compared to the importance of readability, where + also seems a clear winner here.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!