. Net – does the StringBuilder initialized with a string contain the exact (only) space for the string?

I wonder if this code

StringBuilder sb = new StringBuilder("Please read the following messages.");

... initialize sb with a buffer exactly as large as the string passed to the constructor On the one hand, this seems to be the most logical thing On the other hand, it seems to beat the purpose of the StringBuilder class. One of its most common uses is to provide variability to make repeated additions more effective (when I call append for the first time, if the answer to my question is "yes", I need sb to resize myself.)

Then again, I think I can think of it as a constructor similar to list < T > IEnumerable < T > is used as the parameter Perhaps the assumption in this case is that you don't intend to add a lot, but manipulate what already exists

The only real research I have done in this area is to check MSDN documentation on StringBuilder, which does not provide an answer (it means that the constructor initializes the instance with the specified string, but does not indicate how to use the string)

Editor: so this is "implementation specific"... Doesn't it seem strange to others? I mean, the purpose of the StringBuilder class is to provide alternative methods to perform a large number of operations on strings, and create a large number of immutable string instances in the process; Therefore, this is to improve efficiency I think the behavior of this constructor should be specified so that developers can make informed decisions about how to use it regardless of the platform

I mean, it's implemented by Microsoft in some way; They can easily put it into documentation (forcing other implementations to follow) Just a source of personal confusion

Solution

This is an implementation detail you don't have to worry about However, use Net reflector, and look at the (string, int32, int32) overload of the constructor (called by other constructors). We can see that the selected capacity is a multiple of 16 (the next maximum request size)

edit

In fact, it is 16 x 2 ^ n, and select the value of "n" as the next maximum size

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>