• Post Reply Bookmark Topic Watch Topic
  • New Topic

Concatenation- reg  RSS feed

 
Akshayan Venkatesh
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For concatenation of strings, which method is good,
StringBuffer or String ? and Why

please explain me in advance
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prefer StringBuffers (or StringBuilders) in general, since String concatenation can create large numbers of short lived immutable objects. In some cases this is fixed by the compiler but it is better not to rely on this.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally, I think that concatenation of a small number of Strings is best done with the "+" operator and Strings. This is because it makes the code more concise and readable, which is usually much more important than micro-optimising it.

If you have hundreds of Strings to concatenate, or if you have good evidence that you are in a performance-critical piece of code (*), then StringBuilder is best, because it is faster. Or, if you do use Java 1.4 or worse, StringBuffer.

(*) In most programs, only a tiny fraction of the code has any noticable effect on performance. And it's usually not the part that the developer thinks, either.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!