Style_ClassSelector.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Collections.Generic;
  2. using System.Runtime.CompilerServices;
  3. using Avalonia.Controls;
  4. using Avalonia.PropertyStore;
  5. using Avalonia.Styling;
  6. using Avalonia.UnitTests;
  7. using BenchmarkDotNet.Attributes;
  8. #nullable enable
  9. namespace Avalonia.Benchmarks.Styling
  10. {
  11. [MemoryDiagnoser]
  12. public class Style_ClassSelector
  13. {
  14. private Style _style = null!;
  15. public Style_ClassSelector()
  16. {
  17. RuntimeHelpers.RunClassConstructor(typeof(TestClass).TypeHandle);
  18. }
  19. [GlobalSetup]
  20. public void Setup()
  21. {
  22. _style = new Style(x => x.OfType<TestClass>().Class("foo"))
  23. {
  24. Setters = { new Setter(TestClass.StringProperty, "foo") }
  25. };
  26. }
  27. [Benchmark(OperationsPerInvoke = 50)]
  28. public void Apply()
  29. {
  30. var target = new TestClass();
  31. target.GetValueStore().BeginStyling();
  32. for (var i = 0; i < 50; ++i)
  33. StyleHelpers.TryAttach(_style, target);
  34. target.GetValueStore().EndStyling();
  35. }
  36. [Benchmark(OperationsPerInvoke = 50)]
  37. public void Apply_Toggle()
  38. {
  39. var target = new TestClass();
  40. target.GetValueStore().BeginStyling();
  41. for (var i = 0; i < 50; ++i)
  42. StyleHelpers.TryAttach(_style, target);
  43. target.GetValueStore().EndStyling();
  44. target.Classes.Add("foo");
  45. target.Classes.Remove("foo");
  46. }
  47. [Benchmark(OperationsPerInvoke = 50)]
  48. public void Apply_Detach()
  49. {
  50. var target = new TestClass();
  51. target.GetValueStore().BeginStyling();
  52. for (var i = 0; i < 50; ++i)
  53. StyleHelpers.TryAttach(_style, target);
  54. target.GetValueStore().EndStyling();
  55. target.DetachStyles();
  56. }
  57. private class TestClass : Control
  58. {
  59. public static readonly StyledProperty<string?> StringProperty =
  60. AvaloniaProperty.Register<TestClass, string?>("String");
  61. public void DetachStyles() => InvalidateStyles();
  62. }
  63. private class TestClass2 : Control
  64. {
  65. }
  66. }
  67. }