1

Below are two ways how to append String:

String firstString = "text_0";
String secondString = "text_1";
String resultString = firstString + secondString;

StringBuilder sb = new StringBuilder();
sb.append(firstString).append(secondString);
String resultString = sb.toString();

My question is - when is more effective to use StringBuilder? Let's say there are 10 strings, and I need to create one of them.

Ernestas Gruodis
  • 8,567
  • 14
  • 55
  • 117
  • 2
    http://stackoverflow.com/questions/4645020/when-to-use-stringbuilder-in-java – VM4 Aug 27 '13 at 14:18
  • http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java – Lera Aug 27 '13 at 14:20

2 Answers2

2

Because StringBuilder can "append" a string instead of concatenating two strings each time creating a new object. Even if you use += operator with Strings a new object is created. This advantage will only become relevant once you try to concatenate a great number of strings. If is also consiedered a bit more readable.

Peter Jaloveczki
  • 2,039
  • 1
  • 19
  • 35
  • I've tried [this](http://stackoverflow.com/a/1532547/2111085) example to test the speed. So my results are: slow elapsed 29672 ms; fast elapsed 15 ms. So the answer is obvious. But if it would be 100 iterations - time is the same - 0 ms. If 500 iterations - 16 ms and 0 ms. And so on. – Ernestas Gruodis Aug 27 '13 at 14:36
0

Two main Advantages:

  1. Mutable
  2. Not Synchronized.
JNL
  • 4,683
  • 18
  • 29