StringBuilder ⚒️
The StringBuffer / StringBuilder classes are primarily used to modify string values without having to initialize a new String object every time. They simply create a resizable array of all the strings, copying them back to a string only when necessary.
Java and immutable strings
Example in Java without string builder
This function concatenate a list of strings.
The strings are all the same length (call this x) and that there are n strings.
String joinWords(String[] words) {
String sentence = "";
for (String w : words)
sentence = sentence + w;
return sentence;
}
Since in Java strings are immutable, in this piece of code a new copy of the string is created on each concatenation, and the two strings are copied over, character by character. The first iteration requires us to copy x characters, the second 2x characters, and so on.
- Time complexity:
(sum of 1 through n equals , or )
Example in Java with string builder
As said before, StringBuilder simply creates a resizable array of all the strings, copying them back only when necessary.
String joinWords(String[] words) {
StringBuilder sentence = new StringBuilder();
for (String w: words)
sentence.append(w);
return sentence.toString();
}
- Time complexity:
C++ and mutable strings
C++ strings are mutable so the performance considerations of concatenation are less of a concern. However, you can decide to use std::stringstream.