SelectorBenchmark.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using Avalonia.Controls;
  3. using Avalonia.Styling;
  4. using BenchmarkDotNet.Attributes;
  5. namespace Avalonia.Benchmarks.Styling
  6. {
  7. [MemoryDiagnoser]
  8. public class SelectorBenchmark
  9. {
  10. private readonly Control _notMatchingControl;
  11. private readonly Calendar _matchingControl;
  12. private readonly Selector _isCalendarSelector;
  13. private readonly Selector _classSelector;
  14. private readonly Selector _orSelectorTwo;
  15. private readonly Selector _orSelectorFive;
  16. public SelectorBenchmark()
  17. {
  18. _notMatchingControl = new Control();
  19. _matchingControl = new Calendar();
  20. const string className = "selector-class";
  21. _matchingControl.Classes.Add(className);
  22. _isCalendarSelector = Selectors.Is<Calendar>(null);
  23. _classSelector = Selectors.Class(null, className);
  24. _orSelectorTwo = Selectors.Or(new AlwaysMatchSelector(), new AlwaysMatchSelector());
  25. _orSelectorFive = Selectors.Or(
  26. new AlwaysMatchSelector(),
  27. new AlwaysMatchSelector(),
  28. new AlwaysMatchSelector(),
  29. new AlwaysMatchSelector(),
  30. new AlwaysMatchSelector());
  31. }
  32. [Benchmark]
  33. public void IsSelector_NoMatch()
  34. {
  35. _isCalendarSelector.Match(_notMatchingControl);
  36. }
  37. [Benchmark]
  38. public void IsSelector_Match()
  39. {
  40. _isCalendarSelector.Match(_matchingControl);
  41. }
  42. [Benchmark]
  43. public void ClassSelector_NoMatch()
  44. {
  45. _classSelector.Match(_notMatchingControl);
  46. }
  47. [Benchmark]
  48. public void ClassSelector_Match()
  49. {
  50. _classSelector.Match(_matchingControl);
  51. }
  52. [Benchmark]
  53. public void OrSelector_One_Match()
  54. {
  55. _orSelectorTwo.Match(_matchingControl);
  56. }
  57. [Benchmark]
  58. public void OrSelector_Five_Match()
  59. {
  60. _orSelectorFive.Match(_matchingControl);
  61. }
  62. }
  63. internal class AlwaysMatchSelector : Selector
  64. {
  65. internal override bool InTemplate => false;
  66. internal override bool IsCombinator => false;
  67. internal override Type TargetType => null;
  68. public override string ToString(Style owner)
  69. {
  70. return "Always";
  71. }
  72. private protected override SelectorMatch Evaluate(StyledElement control, IStyle parent, bool subscribe)
  73. {
  74. return SelectorMatch.AlwaysThisType;
  75. }
  76. private protected override Selector MovePrevious() => null;
  77. private protected override Selector MovePreviousOrParent() => null;
  78. }
  79. }