JsValueArrayPool.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. if (array.Length == 1)
  56. {
  57. _poolArray1.Free(array);
  58. }
  59. else if (array.Length == 2)
  60. {
  61. _poolArray2.Free(array);
  62. }
  63. else if (array.Length == 3)
  64. {
  65. _poolArray3.Free(array);
  66. }
  67. }
  68. }