ListInteropBenchmark.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System.Collections;
  2. using BenchmarkDotNet.Attributes;
  3. using Jint.Native;
  4. using Jint.Runtime.Interop;
  5. namespace Jint.Benchmark;
  6. [MemoryDiagnoser]
  7. public class ListInteropBenchmark
  8. {
  9. private static bool IsArrayLike(Type type)
  10. {
  11. if (typeof(IDictionary).IsAssignableFrom(type))
  12. {
  13. return false;
  14. }
  15. if (typeof(ICollection).IsAssignableFrom(type))
  16. {
  17. return true;
  18. }
  19. foreach (var typeInterface in type.GetInterfaces())
  20. {
  21. if (!typeInterface.IsGenericType)
  22. {
  23. continue;
  24. }
  25. if (typeInterface.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>)
  26. || typeInterface.GetGenericTypeDefinition() == typeof(ICollection<>))
  27. {
  28. return true;
  29. }
  30. }
  31. return false;
  32. }
  33. private const int Count = 10_00;
  34. private Engine _engine;
  35. private JsValue[] _properties;
  36. [GlobalSetup]
  37. public void Setup()
  38. {
  39. _engine = new Engine(options =>
  40. {
  41. options
  42. .SetWrapObjectHandler((engine, target, type) =>
  43. {
  44. var instance = new ObjectWrapper(engine, target);
  45. var isArrayLike = IsArrayLike(instance.Target.GetType());
  46. if (isArrayLike)
  47. {
  48. instance.Prototype = engine.Intrinsics.Array.PrototypeObject;
  49. }
  50. return instance;
  51. })
  52. ;
  53. });
  54. _properties = new JsValue[Count];
  55. var input = new List<Data>(Count);
  56. for (var i = 0; i < Count; ++i)
  57. {
  58. input.Add(new Data { Category = new Category { Name = i % 2 == 0 ? "Pugal" : "Beagle" } });
  59. _properties[i] = JsNumber.Create(i);
  60. }
  61. _engine.SetValue("input", input);
  62. _engine.SetValue("CONST", new { category = "Pugal" });
  63. }
  64. [Benchmark]
  65. public void Filter()
  66. {
  67. var value = (Data) _engine.Evaluate("input.filter(i => i.category?.name === CONST.category)[0]").ToObject();
  68. if (value.Category.Name != "Pugal")
  69. {
  70. throw new InvalidOperationException();
  71. }
  72. }
  73. [Benchmark]
  74. public void Indexing()
  75. {
  76. _engine.Evaluate("for (var i = 0; i < input.length; ++i) { input[i]; }");
  77. }
  78. [Benchmark]
  79. public void HasProperty()
  80. {
  81. var input = (ObjectWrapper) _engine.GetValue("input");
  82. for (var i = 0; i < _properties.Length; ++i)
  83. {
  84. if (!input.HasProperty(_properties[i]))
  85. {
  86. throw new InvalidOperationException();
  87. }
  88. }
  89. }
  90. private class Data
  91. {
  92. public Category Category { get; set; }
  93. }
  94. private class Category
  95. {
  96. public string Name { get; set; }
  97. }
  98. }