JsValueArrayPool.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Runtime.CompilerServices;
  2. using Jint.Native;
  3. namespace Jint.Pooling;
  4. /// <summary>
  5. /// Cache reusable <see cref="JsValue" /> array instances as we allocate them a lot.
  6. /// </summary>
  7. internal sealed class JsValueArrayPool
  8. {
  9. private const int PoolSize = 15;
  10. private readonly ObjectPool<JsValue[]> _poolArray1;
  11. private readonly ObjectPool<JsValue[]> _poolArray2;
  12. private readonly ObjectPool<JsValue[]> _poolArray3;
  13. public JsValueArrayPool()
  14. {
  15. _poolArray1 = new ObjectPool<JsValue[]>(Factory1, PoolSize);
  16. _poolArray2 = new ObjectPool<JsValue[]>(Factory2, PoolSize);
  17. _poolArray3 = new ObjectPool<JsValue[]>(Factory3, PoolSize);
  18. }
  19. private static JsValue[] Factory1()
  20. {
  21. return new JsValue[1];
  22. }
  23. private static JsValue[] Factory2()
  24. {
  25. return new JsValue[2];
  26. }
  27. private static JsValue[] Factory3()
  28. {
  29. return new JsValue[3];
  30. }
  31. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  32. public JsValue[] RentArray(int size)
  33. {
  34. if (size == 0)
  35. {
  36. return [];
  37. }
  38. if (size == 1)
  39. {
  40. return _poolArray1.Allocate();
  41. }
  42. if (size == 2)
  43. {
  44. return _poolArray2.Allocate();
  45. }
  46. if (size == 3)
  47. {
  48. return _poolArray3.Allocate();
  49. }
  50. return new JsValue[size];
  51. }
  52. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  53. public void ReturnArray(JsValue[] array)
  54. {
  55. // Ensure that the array contents are cleared
  56. // to allow garbage collecting the values of the
  57. // array if possible. Only the array itself
  58. // should be cached.
  59. if (array.Length == 1)
  60. {
  61. array[0] = null!;
  62. _poolArray1.Free(array);
  63. }
  64. else if (array.Length == 2)
  65. {
  66. array[0] = null!;
  67. array[1] = null!;
  68. _poolArray2.Free(array);
  69. }
  70. else if (array.Length == 3)
  71. {
  72. array[0] = null!;
  73. array[1] = null!;
  74. array[2] = null!;
  75. _poolArray3.Free(array);
  76. }
  77. }
  78. }