ArgumentsInstancePool.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using Jint.Native;
  2. using Jint.Native.Function;
  3. using Jint.Runtime.Environments;
  4. namespace Jint.Pooling;
  5. /// <summary>
  6. /// Cache reusable <see cref="JsArguments" /> instances as we allocate them a lot.
  7. /// </summary>
  8. internal sealed class ArgumentsInstancePool
  9. {
  10. private const int PoolSize = 10;
  11. private readonly Engine _engine;
  12. private readonly ObjectPool<JsArguments> _pool;
  13. public ArgumentsInstancePool(Engine engine)
  14. {
  15. _engine = engine;
  16. _pool = new ObjectPool<JsArguments>(Factory, PoolSize);
  17. }
  18. private JsArguments Factory()
  19. {
  20. return new JsArguments(_engine)
  21. {
  22. _prototype = _engine.Realm.Intrinsics.Object.PrototypeObject
  23. };
  24. }
  25. public JsArguments Rent(JsValue[] argumentsList) => Rent(null, null, argumentsList, null, false);
  26. public JsArguments Rent(
  27. Function? func,
  28. Key[]? formals,
  29. JsValue[] argumentsList,
  30. DeclarativeEnvironment? env,
  31. bool hasRestParameter)
  32. {
  33. var obj = _pool.Allocate();
  34. obj.Prepare(func!, formals!, argumentsList, env!, hasRestParameter);
  35. return obj;
  36. }
  37. public void Return(JsArguments instance)
  38. {
  39. if (instance is null)
  40. {
  41. return;
  42. }
  43. _pool.Free(instance);
  44. }
  45. }