为什么我们需要StringBuilder中的容量 [英] Why do we need capacity in StringBuilder
问题描述
我们知道,StringBuilder中有一个称为容量的属性,该属性始终大于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?
推荐答案
您可以使用初始容量来节省在附加 StringBuilder
的同时调整其大小的需求,这会花费时间.
You can use the initial capacity to save the need to re-size the StringBuilder
while appending to it, which costs time.
如果预先知道要在 StringBuilder
后面附加多少个字符,并且在创建 StringBuilder
时指定该大小,则不必重新输入-使用时调整大小.
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.
如果另一方面,您没有提供初始容量或初始容量太小,则每次达到该容量时,都必须增加 StringBuilder
的存储量,这涉及将存储在原始存储中的数据复制到更大的存储中.
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.
这篇关于为什么我们需要StringBuilder中的容量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!