ListInteropBenchmark.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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();
  40. _properties = new JsValue[Count];
  41. var input = new List<Data>(Count);
  42. for (var i = 0; i < Count; ++i)
  43. {
  44. input.Add(new Data { Category = new Category { Name = i % 2 == 0 ? "Pugal" : "Beagle" } });
  45. _properties[i] = JsNumber.Create(i);
  46. }
  47. _engine.SetValue("input", input);
  48. _engine.SetValue("CONST", new { category = "Pugal" });
  49. }
  50. [Benchmark]
  51. public void Filter()
  52. {
  53. var value = (Data) _engine.Evaluate("input.filter(i => i.category?.name === CONST.category)[0]").ToObject();
  54. if (value.Category.Name != "Pugal")
  55. {
  56. throw new InvalidOperationException();
  57. }
  58. }
  59. [Benchmark]
  60. public void Indexing()
  61. {
  62. _engine.Evaluate("for (var i = 0; i < input.length; ++i) { input[i]; }");
  63. }
  64. [Benchmark]
  65. public void HasProperty()
  66. {
  67. var input = (ObjectWrapper) _engine.GetValue("input");
  68. for (var i = 0; i < _properties.Length; ++i)
  69. {
  70. if (!input.HasProperty(_properties[i]))
  71. {
  72. throw new InvalidOperationException();
  73. }
  74. }
  75. }
  76. private class Data
  77. {
  78. public Category Category { get; set; }
  79. }
  80. private class Category
  81. {
  82. public string Name { get; set; }
  83. }
  84. }