Memory allocation The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32.
Default capacity of a String-Builder is 16 characters , And Max capacity of String-Builder is 2147483647 characters.
C# StringBuilder is similar to Java StringBuilder. A String object is immutable, i.e. a String cannot be changed once created. Every time when you use any of the methods of the System. String class, then you create a new string object in memory.
The StringBuilder works by maintaining a buffer of characters (Char) that will form the final string. Characters can be appended, removed and manipulated via the StringBuilder, with the modifications being reflected by updating the character buffer accordingly. An array is used for this character buffer.
Should StringBuilder.Capacity
be set to the maximum number of .NET characters, without regards to null termination, or must it be set one higher to reserve space for a null terminator when using P/Invoke.
The natural reaction is that it should be set one higher, but it seems like P/Invoke is supposed to automatically compensate. In fact this is actually documented right here: http://msdn.microsoft.com/en-US/library/s9ts558h(v=VS.100).aspx
The reason for this question is that most examples are not strictly consistent with the above documentation. Almost always they are coded:
StringBuilder sb = new StringBuilder(dotNetChars + 1);
SomeWindowsAPI(sb, sb.Capacity);
Instead of:
StringBuilder sb = new StringBuilder(dotNetChars);
SomeWindowsAPI(sb, sb.Capacity + 1);
(I realize that some APIs handle the buffer size parameter differently. Assume that the API handles this the must common way, like GetFullPathName
: http://msdn.microsoft.com/en-us/library/aa364963(v=VS.85).aspx)
Using an expression with sb.Capacity
directly in the API call seems to be a best practice to avoid a mismatch. The issue is whether or not adding the +1 is correct.
Look around. You'll probably find that the only place showing sb.Capacity + 1
is the MSDN documentation.
Of course, one can allocate on the side of caution with a larger buffer than is strictly necessary, but I would like to know the consensus on how to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With