Understanding the internal configuration of the StringBuilderCache.NET class

When I looked at decompiled .NET assemblies to see some internal elements, I noticed an interesting StringBuilderCache class used by several frameworks:

 internal static class StringBuilderCache { [ThreadStatic] private static StringBuilder CachedInstance; private const int MAX_BUILDER_SIZE = 360; public static StringBuilder Acquire(int capacity = 16) { if (capacity <= 360) { StringBuilder cachedInstance = StringBuilderCache.CachedInstance; if (cachedInstance != null && capacity <= cachedInstance.Capacity) { StringBuilderCache.CachedInstance = null; cachedInstance.Clear(); return cachedInstance; } } return new StringBuilder(capacity); } public static void Release(StringBuilder sb) { if (sb.Capacity <= 360) { StringBuilderCache.CachedInstance = sb; } } public static string GetStringAndRelease(StringBuilder sb) { string result = sb.ToString(); StringBuilderCache.Release(sb); return result; } } 

We can find an example of use, for example, in the string.Format method:

 public static string Format(IFormatProvider provider, string format, params object[] args) { ... StringBuilder stringBuilder = StringBuilderCache.Acquire(format.Length + args.Length * 8); stringBuilder.AppendFormat(provider, format, args); return StringBuilderCache.GetStringAndRelease(stringBuilder); } 

Although it’s pretty smart and I’ll probably remember that caching scheme, I wonder why MAX_BUILDER_SIZE so small? Having installed it, let it install 2kB, wouldn’t it be better? This would prevent the creation of large instances of StringBuilder with fairly low memory overhead.

+7
stringbuilder c # .net-internals
source share
2 answers

This is a cache stream, so a small number is expected. It is best to use the Reference Source for questions like this, you will also see comments. Which looks like (edited to match):

  // The value 360 was chosen in discussion with performance experts as a // compromise between using as litle memory (per thread) as possible and // still covering a large part of short-lived StringBuilder creations on // the startup path of VS designers. private const int MAX_BUILDER_SIZE = 360; 

"VS Constructors" is a bit strange. Well, actually, this work was not done to optimize Visual Studio. Neeli Cruz will have a field day, and the EU will have another billion dollars if she finds out :)

+16
source share

Most of the lines built are probably small, so using a relatively small buffer size will cover most operations without using too much memory. Note that there is a thread pool with the possible creation of multiple threads. If each of them takes up to 2 KB for the cached buffer, this will add up to a certain amount of memory.

+4
source share

All Articles