Style_Apply.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using Avalonia.Controls;
  5. using Avalonia.Styling;
  6. using BenchmarkDotNet.Attributes;
  7. #nullable enable
  8. namespace Avalonia.Benchmarks.Styling
  9. {
  10. [MemoryDiagnoser]
  11. public class Style_Apply
  12. {
  13. private List<Style> _styles = new();
  14. public Style_Apply()
  15. {
  16. RuntimeHelpers.RunClassConstructor(typeof(TestClass).TypeHandle);
  17. }
  18. [Params(1, 5, 50)]
  19. public int MatchingStyles { get; set; }
  20. [Params(1, 5, 50)]
  21. public int NonMatchingStyles { get; set; }
  22. [GlobalSetup]
  23. public void Setup()
  24. {
  25. _styles.Clear();
  26. for (var i = 0; i < MatchingStyles; ++i)
  27. {
  28. _styles.Add(new Style(x => x.OfType<TestClass>())
  29. {
  30. Setters = { new Setter(TestClass.StringProperty, "foo") }
  31. });
  32. }
  33. for (var i = 0; i < NonMatchingStyles; ++i)
  34. {
  35. _styles.Add(new Style(x => x.OfType<TestClass2>().Class("missing"))
  36. {
  37. Setters = { new Setter(TestClass.StringProperty, "foo") }
  38. });
  39. }
  40. }
  41. [Benchmark]
  42. public void Apply_Simple_Styles()
  43. {
  44. var target = new TestClass();
  45. target.GetValueStore().BeginStyling();
  46. foreach (var style in _styles)
  47. style.TryAttach(target, null);
  48. target.GetValueStore().EndStyling();
  49. }
  50. private class TestClass : Control
  51. {
  52. public static readonly StyledProperty<string?> StringProperty =
  53. AvaloniaProperty.Register<TestClass, string?>("String");
  54. public static readonly StyledProperty<Struct1> Struct1Property =
  55. AvaloniaProperty.Register<TestClass, Struct1>("Struct1");
  56. public static readonly StyledProperty<Struct2> Struct2Property =
  57. AvaloniaProperty.Register<TestClass, Struct2>("Struct2");
  58. public static readonly StyledProperty<Struct3> Struct3Property =
  59. AvaloniaProperty.Register<TestClass, Struct3>("Struct3");
  60. public static readonly StyledProperty<Struct4> Struct4Property =
  61. AvaloniaProperty.Register<TestClass, Struct4>("Struct4");
  62. public static readonly StyledProperty<Struct5> Struct5Property =
  63. AvaloniaProperty.Register<TestClass, Struct5>("Struct5");
  64. public static readonly StyledProperty<Struct6> Struct6Property =
  65. AvaloniaProperty.Register<TestClass, Struct6>("Struct6");
  66. public static readonly StyledProperty<Struct7> Struct7Property =
  67. AvaloniaProperty.Register<TestClass, Struct7>("Struct7");
  68. public static readonly StyledProperty<Struct8> Struct8Property =
  69. AvaloniaProperty.Register<TestClass, Struct8>("Struct8");
  70. }
  71. private class TestClass2 : Control
  72. {
  73. }
  74. }
  75. }