Java StringBuilder capacity

This Java example page shows how StringBuilder approximately doubles its capacity when you append data to it.
StringBuilder, capacity. A StringBuilder grows its buffer automatically as we add data to it. In Java, we find it doubles the buffer size and adds 2 when more capacity is needed.
Usually, we do not need to worry about capacities with StringBuilder. But to determine an optimal starting capacity, you can print out the actual capacity during program execution.
An example. This program creates an empty StringBuilder. It uses for-loop to add 20 strings of 5 characters each to the StringBuilder.

And: It prints out the length, and the capacity on each iteration. We see how the capacity changes.

Java program that measures capacity after appends import java.lang.StringBuilder; public class Program { public static void main(String[] args) { StringBuilder builder = new StringBuilder(""); for (int i = 0; i < 20; i++) { // Print length and capacity. System.out.println("Length = " + builder.length() + "; Capacity = " + builder.capacity()); // Add 5 chars to StringBuilder. builder.append("xxxyy"); } } } Output Length = 0; Capacity = 16 Length = 5; Capacity = 16 Length = 10; Capacity = 16 Length = 15; Capacity = 16 Length = 20; Capacity = 34 Length = 25; Capacity = 34 Length = 30; Capacity = 34 Length = 35; Capacity = 70 Length = 40; Capacity = 70 Length = 45; Capacity = 70 Length = 50; Capacity = 70 Length = 55; Capacity = 70 Length = 60; Capacity = 70 Length = 65; Capacity = 70 Length = 70; Capacity = 70 Length = 75; Capacity = 142 Length = 80; Capacity = 142 Length = 85; Capacity = 142 Length = 90; Capacity = 142 Length = 95; Capacity = 142
Notes. The StringBuilder starts out with a capacity of 16. It then doubles (and adds 2) to get a capacity of 34. It only increases capacity when the length exceeds its current capacity.
A review. For StringBuilder, a capacity is an important detail. This type's main advantage over a String is that it has a capacity—it can accommodate extra data, avoiding allocations.StringBuilder
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls