StringBuilderUtils.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Text;
  3. namespace XGame.Framework.Utils
  4. {
  5. public static class StringBuilderUtils
  6. {
  7. private const int CAPACITY_LIMIT = 360;
  8. [ThreadStatic]
  9. private static StringBuilder CachedInstance;
  10. private const int DefaultCapacity = 16;
  11. public static StringBuilder Acquire(int capacity = DefaultCapacity)
  12. {
  13. if (capacity <= CAPACITY_LIMIT)
  14. {
  15. StringBuilder sb = CachedInstance;
  16. if (sb != null)
  17. {
  18. // Avoid stringbuilder block fragmentation by getting a new StringBuilder
  19. // when the requested size is larger than the current capacity
  20. if (capacity <= sb.Capacity)
  21. {
  22. CachedInstance = null;
  23. sb.Clear();
  24. return sb;
  25. }
  26. }
  27. }
  28. return new StringBuilder(capacity);
  29. }
  30. public static void Release(StringBuilder sb)
  31. {
  32. if (sb.Capacity <= CAPACITY_LIMIT)
  33. {
  34. CachedInstance = sb;
  35. }
  36. }
  37. public static string GetStringAndRelease(StringBuilder sb)
  38. {
  39. string result = sb.ToString();
  40. Release(sb);
  41. return result;
  42. }
  43. }
  44. }