JsValueArrayPool.cs 2.1 KB

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