Home
Do you know when to use StringBuilder?
  v1.0 Posted at 14/01/2019 12:42 PM by Calum Simpson
​​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 ++) {
  sb.append(i);
}​

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

See here for more details.


Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments: