Capacity Management: ensureCapacity and trimToSize
What you'll learn: How to control StringBuilder's internal memory allocation to optimize performance and memory usage.
Understanding Internal Capacity
Every StringBuilder has an internal character array that holds its content. This array has a capacity (total slots available) that's usually larger than the current length (actual characters stored). Think of it like a parking lot: capacity is total spaces, length is occupied spaces.
When you append beyond capacity, StringBuilder automatically allocates a new, larger array and copies everything over—an expensive operation. If you know you'll need lots of space upfront, you can avoid these reallocations.
Minimizing Reallocations with ensureCapacity
The ensureCapacity(int minimumCapacity) method pre-allocates space before you start building:
StringBuilder sb = new StringBuilder(); // default capacity: 16
sb.ensureCapacity(1000); // pre-allocate for 1000 characters
// Now append 1000 chars with NO internal reallocations
for (int i = 0; i < 1000; i++) {
sb.append('x');
}
This is like reserving enough parking spaces before the crowd arrives—no scrambling for more space later.
Reclaiming Memory with trimToSize
After you're done building, the internal array might be much larger than needed. The trimToSize() method shrinks the capacity to exactly match the current length, freeing unused memory:
StringBuilder sb = new StringBuilder(1000);
sb.append("small"); // length: 5, capacity: 1000
sb.trimToSize(); // capacity now: 5
Think of it as downsizing from a warehouse to a closet once you know exactly what you're storing.
When to Use These
Use ensureCapacity when you know the approximate final size beforehand (batch processing, reading files). Use trimToSize when you'll keep the StringBuilder around for a while and memory is tight.
Key Takeaway: ensureCapacity prevents costly reallocations during construction, while trimToSize reclaims wasted memory after you're done building—together they give you fine-grained control over StringBuilder's memory footprint.