Search code examples
memory-managementasp.net-core.net-corestringbuilder

Whats the difference between InplaceStringBuilder and StringBuilder?


Today in VS2017 intellisense surfaced InplaceStringBuilder when I was trying to type StringBuilder. InplaceStringBuilder is new to me so I started digging to see what I could learn.

The first thing I noticed is that it's a struct and not a class and it's type information looks like this:

#region Assembly Microsoft.Extensions.Primitives, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Users\Ron Clabo\Documents\Visual Studio 2017\Projects\wwwGiftOasisResponsive\packages\Microsoft.Extensions.Primitives.1.1.0\lib\netstandard1.0\Microsoft.Extensions.Primitives.dll
#endregion

using System.Diagnostics;

namespace Microsoft.Extensions.Primitives {
    [DebuggerDisplay("Value = {_value}")]
    public struct InplaceStringBuilder {
        public InplaceStringBuilder(int capacity);

        public int Capacity { get; set; }

        public void Append(string s);
        public void Append(char c);
        public override string ToString();
    }
}

So it has alot fewer methods than StringBuilder. Then I googled around to learn more about InplaceStringBuilder but there's not much on the web about it yet, so it looks to be pretty new.

Besides, the differences I have already mentioned, what are the differences between InplaceStringBuilder and StringBuilder; and when should a developer use the new InplaceStringBuilder instead of the age old StringBuilder?


Solution

  • The normal StringBuilder increases the capacity when the resulting string is longer than the initial capacity. The InplaceStringBuilder is limited to its capacity and throws an exception if the resulting string is longer.

    This is quite a limitation of InplaceStringBuilder, so it may only be suitable in rare cases. In addition, if you know the capacity in advance, it was already possible to define the initial capacity of a normal StringBuilder.

    Source: look at the implementation of InplaceStringBuilder on GitHub and compare to StringBuilder on MSDN