StringBuilderCache.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using System.Text;
  5. namespace PlatformBenchmarks
  6. {
  7. internal static class StringBuilderCache
  8. {
  9. private const int DefaultCapacity = 1386;
  10. private const int MaxBuilderSize = DefaultCapacity * 3;
  11. [ThreadStatic]
  12. private static StringBuilder t_cachedInstance;
  13. /// <summary>Get a StringBuilder for the specified capacity.</summary>
  14. /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks>
  15. public static StringBuilder Acquire(int capacity = DefaultCapacity)
  16. {
  17. if (capacity <= MaxBuilderSize)
  18. {
  19. StringBuilder sb = t_cachedInstance;
  20. if (capacity < DefaultCapacity)
  21. {
  22. capacity = DefaultCapacity;
  23. }
  24. if (sb != null)
  25. {
  26. // Avoid stringbuilder block fragmentation by getting a new StringBuilder
  27. // when the requested size is larger than the current capacity
  28. if (capacity <= sb.Capacity)
  29. {
  30. t_cachedInstance = null;
  31. sb.Clear();
  32. return sb;
  33. }
  34. }
  35. }
  36. return new StringBuilder(capacity);
  37. }
  38. public static void Release(StringBuilder sb)
  39. {
  40. if (sb.Capacity <= MaxBuilderSize)
  41. {
  42. t_cachedInstance = sb;
  43. }
  44. }
  45. public static string GetStringAndRelease(StringBuilder sb)
  46. {
  47. string result = sb.ToString();
  48. Release(sb);
  49. return result;
  50. }
  51. }
  52. }