ArgumentsInstancePool.cs 1.5 KB

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