Note that there are some explanatory texts on larger screens.

plurals
  1. POUnderstanding of .NET internal StringBuilderCache class configuration
    primarykey
    data
    text
    <p>When I was looking at decompiled .NET assemblies to see some internals, I've noticed interesting <code>StringBuilderCache</code> class used by multiple framework's methods:</p> <pre><code>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 &lt;= 360) { StringBuilder cachedInstance = StringBuilderCache.CachedInstance; if (cachedInstance != null &amp;&amp; capacity &lt;= cachedInstance.Capacity) { StringBuilderCache.CachedInstance = null; cachedInstance.Clear(); return cachedInstance; } } return new StringBuilder(capacity); } public static void Release(StringBuilder sb) { if (sb.Capacity &lt;= 360) { StringBuilderCache.CachedInstance = sb; } } public static string GetStringAndRelease(StringBuilder sb) { string result = sb.ToString(); StringBuilderCache.Release(sb); return result; } } </code></pre> <p>Example usage we can find for example in <code>string.Format</code> method:</p> <pre><code>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); } </code></pre> <p>While it is quite clever and for sure I will remember about such caching pattern, I wonder why <code>MAX_BUILDER_SIZE</code> is so small? Setting it to, let's set 2kB, wouldn't be better? It would prevent from creating bigger <code>StringBuilder</code> instances with a quite little memory overhead.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload