StringBuilder capacity
See why appending is cheap, when the buffer is copied, and how to avoid the copy.
Open this lesson in the learning hubKey points
StringBuilderwraps a character array.length()is what you stored,capacity()is what is allocated.- A fresh builder starts at capacity 16, or at the length of the seed string plus 16.
- When an append does not fit, a bigger array is allocated and the contents copied. The new capacity is
old * 2 + 2. - Pre-size with
new StringBuilder(1000)when you roughly know the result and those copies disappear. setLengthchanges the length without shrinking the buffer;trimToSizehands the spare memory back.StringBufferis the synchronised twin. Unless several threads share the buffer,StringBuilderis the right pick.
Example
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println("empty -> length " + sb.length() + ", capacity " + sb.capacity());
sb.append("0123456789");
System.out.println("10 chars -> length " + sb.length() + ", capacity " + sb.capacity());
sb.append("abcdefghij");
System.out.println("20 chars -> length " + sb.length() + ", capacity " + sb.capacity()
+ " (old * 2 + 2, array copied once)");
StringBuilder sized = new StringBuilder(1000);
System.out.println("pre-sized -> length " + sized.length() + ", capacity " + sized.capacity());
sb.setLength(3);
System.out.println("setLength(3) -> \"" + sb + "\", capacity still " + sb.capacity());
sb.trimToSize();
System.out.println("trimToSize -> capacity " + sb.capacity());
System.out.println("chained: " + new StringBuilder("stressed").reverse());
System.out.println("length is what you stored, capacity is what is allocated");
}
}
Appending is cheap on average; pre-sizing removes the copies entirely.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.