Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need capacity in StringBuilder

As we know, there is a attribute in StringBuilder called capacity, it is always larger than the length of StringBuilder object. However, what is capacity used for? It will be expanded if the length is larger than the capacity. If it does something, can someone give an example?

like image 610
Jing Avatar asked Dec 19 '14 08:12

Jing


2 Answers

You can use the initial capacity to save the need to re-size the StringBuilder while appending to it, which costs time.

If you know if advance how many characters would be appended to the StringBuilder and you specify that size when you create the StringBuilder, it will never have to be re-sized while it is being used.

If, on the other hand, you don't give an initial capacity, or give a too small intial capacity, each time that capacity is reached, the storage of the StringBuilder has to be increased, which involves copying the data stored in the original storage to the larger storage.

like image 195
Eran Avatar answered Oct 10 '22 05:10

Eran


The string builder has to store the string that is being built somewhere. It does so in an array of characters. The capacity is the length of this array. Once the array would overflow, a new (longer) array is allocated and contents are transferred to it. This makes the capacity rise.

If you are not concerned about performance, simply ignore the capacity. The capacity might get interesting once you are about to construct huge strings and know their size upfront. Then you can request a string builder with a capacity being equal to the expected size (or slightly larger if you are not sure about the size).

Example when building a string with a content size of 1 million:

StringBuilder sb = new StringBuilder(1000000);
for(int i = 0; i < 1000000; i++){
   sb.append("x");
}

Initializing the string builder with one million will make it faster in comparison to a default string builder which has to copy its array repeatedly.

like image 40
gexicide Avatar answered Oct 10 '22 04:10

gexicide