Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

When to use StringBuffer/StringBuilder in stead of Strings  RSS feed

 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe just a question. Why should you use StringBuffer of StringBuilder if you could just use String? Outweighs the overhead of creating a new class the use of different strings, which should be garbage collected at the end.

I'm just curious, because until now I mostly use Strings as of a habit in stead of the StringBuffer/StringBuilder class while man
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've read the following article which states that by repeated updates of the String a stringbuffer/stringbuilder could be more efficient.

String Concatenation/Performance
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's basically it. If you are doing a lot of text manipulations, a StringBuilder is faster. However, this will only translate into measurable performance gains if there are many thousands of updates and/or the Strings are very long.

StringBuilder is better than StringBuffer for most applications, because StringBuffer has unwanted synchronisation.
 
Manuel Leiria
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use the string concatenation operator (+) to combine a few strings into one.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Manuel Leiria:
You can use the string concatenation operator (+) to combine a few strings into one.


Yes, of course you can, but doing so is less efficient than using StringBuilder, if the number of strings to combine is more than a very few.

Good programmers sometimes quite reasonably decide to use concatenation operator even when StringBuilder would be more efficient. They may judge that the conciseness and clarity of concatenation operator is worth a small efficiency loss. Only if the number of concatenations is very large or the strings are very long, will the improved efficiency of StringBuilder make a big performance difference.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!