Why do we need capacity in StringBuilder?

As you know, StringBuilder has an attribute called capacity; it is always greater than the length of the StringBuilder object. However, what is bandwidth for? It will be expanded if the length is greater than the capacity. If he does something, can someone give an example?

+5
source share
4 answers

You can use the initial capacity to save the need to re- StringBuilder when adding to it, which takes time.

If you know how many characters will be added to the StringBuilder , and you specify this size when creating the StringBuilder , you will never have to resize it while it is being used.

If, on the other hand, you do not give the initial capacity or do not make the internal capacity too small, each time this capacity is reached, you need to increase the StringBuilder storage, which is associated with copying the data stored in the original storage to a larger storage.

+9
source

The string constructor should store a string that is being built somewhere. He does this in an array of characters. Capacity is the length of this array. As soon as the array is full, a new (longer) array will be allocated and the contents will be transferred to it. This increases throughput.

If you're not interested in performance, just ignore capacity. Capacity can become interesting when you are going to build huge lines and know your size in advance. You can then request a row builder with a capacity equal to the expected size (or a little more if you are not sure about the size).

An example when building a row with a content size of 1 million:

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

Initializing one million string builders will make it faster than the default string builder, which must copy its array again.

+3
source

StringBuilder supported by an array of characters. The default value is 16 + the length of the String argument. If you add to StringBuilder and the number of characters cannot be placed in an array, then you will need to change the capacity, which will take time. So, if you have an idea of ​​the number of characters you have, initialize the capacity.

+2
source

Answer: performance . As the other answers already say, StringBuilder uses an internal array of some source size (capacity). Each time the string being built becomes large for the array to hold it, StringBuilder must allocate a new larger array, copy the data from the previous array to the new one and delete the previous array.

If you know in advance what size the string can be, and pass this information to the constructor, StringBuilder can immediately create a fairly large array and thus avoid distribution and copying.

While a performance gain is not possible for small lines, this is important if you are creating really large lines.

0
source

Source: https://habr.com/ru/post/1209526/


All Articles