Do you know when to use StringBuilder?

Last updated by Brook Jeynes [SSW] 10 months ago.See history

A String object is immutable - this means if you append two Strings together, the result is an entirely new String, rather than the original String being modified in place. This is inefficient because creating new objects is slower than altering existing objects.

Using StringBuilder to append Strings modifies the underlying Char array rather than creating a new String. Therefore, whenever you are performing multiple String appends or similar functions, you should always use a StringBuilder to improve performance.

String s = "";

for (int i = 0; i < 1000; i ++) {
  s += i;

Figure: Bad example - This inefficient code results in 1000 new String objects being created unnecessarily

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 1000; i ++) {

Figure: Good example - This efficient code only uses one StringBuilder object

See StringBuilder Class for more details.

We open source. Powered by GitHub