|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +namespace System.Text |
| 6 | +{ |
| 7 | + /// <summary>Provide a cached reusable instance of stringbuilder per thread.</summary> |
| 8 | + internal static class StringBuilderCache |
| 9 | + { |
| 10 | + // The value 360 was chosen in discussion with performance experts as a compromise between using |
| 11 | + // as litle memory per thread as possible and still covering a large part of short-lived |
| 12 | + // StringBuilder creations on the startup path of VS designers. |
| 13 | + private const int MaxBuilderSize = 360; |
| 14 | + private const int DefaultCapacity = 16; // == StringBuilder.DefaultCapacity |
| 15 | + |
| 16 | + // WARNING: We allow diagnostic tools to directly inspect this member (t_cachedInstance). |
| 17 | + // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. |
| 18 | + // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. |
| 19 | + // Get in touch with the diagnostics team if you have questions. |
| 20 | + [ThreadStatic] |
| 21 | + private static StringBuilder t_cachedInstance; |
| 22 | + |
| 23 | + /// <summary>Get a StringBuilder for the specified capacity.</summary> |
| 24 | + /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks> |
| 25 | + public static StringBuilder Acquire(int capacity = DefaultCapacity) |
| 26 | + { |
| 27 | + if (capacity <= MaxBuilderSize) |
| 28 | + { |
| 29 | + StringBuilder sb = t_cachedInstance; |
| 30 | + if (sb != null) |
| 31 | + { |
| 32 | + // Avoid stringbuilder block fragmentation by getting a new StringBuilder |
| 33 | + // when the requested size is larger than the current capacity |
| 34 | + if (capacity <= sb.Capacity) |
| 35 | + { |
| 36 | + t_cachedInstance = null; |
| 37 | + sb.Clear(); |
| 38 | + return sb; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + return new StringBuilder(capacity); |
| 43 | + } |
| 44 | + |
| 45 | + /// <summary>Place the specified builder in the cache if it is not too big.</summary> |
| 46 | + public static void Release(StringBuilder sb) |
| 47 | + { |
| 48 | + if (sb.Capacity <= MaxBuilderSize) |
| 49 | + { |
| 50 | + t_cachedInstance = sb; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /// <summary>ToString() the stringbuilder, Release it to the cache, and return the resulting string.</summary> |
| 55 | + public static string GetStringAndRelease(StringBuilder sb) |
| 56 | + { |
| 57 | + string result = sb.ToString(); |
| 58 | + Release(sb); |
| 59 | + return result; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments