ResourceBenchmarks.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using Avalonia.Controls;
  3. using Avalonia.Headless;
  4. using Avalonia.Platform;
  5. using Avalonia.Styling;
  6. using Avalonia.UnitTests;
  7. using BenchmarkDotNet.Attributes;
  8. using Moq;
  9. namespace Avalonia.Benchmarks.Styling
  10. {
  11. [MemoryDiagnoser]
  12. public class ResourceBenchmarks : IDisposable
  13. {
  14. private readonly Control _searchStart;
  15. private readonly IDisposable _app;
  16. private static IDisposable CreateApp()
  17. {
  18. var services = new TestServices(
  19. assetLoader: new StandardAssetLoader(),
  20. globalClock: new MockGlobalClock(),
  21. platform: new StandardRuntimePlatform(),
  22. standardCursorFactory: Mock.Of<ICursorFactory>(),
  23. theme: () => CreateTheme(),
  24. windowingPlatform: new MockWindowingPlatform());
  25. return UnitTestApplication.Start(services);
  26. }
  27. private static Styles CreateTheme()
  28. {
  29. AssetLoader.RegisterResUriParsers();
  30. var preHost = new Style();
  31. preHost.Resources.Add("preTheme", null);
  32. var postHost = new Style();
  33. postHost.Resources.Add("postTheme", null);
  34. return new Styles
  35. {
  36. preHost,
  37. new TestStyles(50, 3, 5, 0),
  38. postHost
  39. };
  40. }
  41. public void Dispose()
  42. {
  43. _app.Dispose();
  44. }
  45. public ResourceBenchmarks()
  46. {
  47. _searchStart = new Button();
  48. _app = CreateApp();
  49. Decorator root = new TestRoot(true, null)
  50. {
  51. Renderer = new NullRenderer()
  52. };
  53. var current = root;
  54. for (int i = 0; i < 10; i++)
  55. {
  56. var child = new Decorator();
  57. current.Child = child;
  58. current = child;
  59. }
  60. current.Child = _searchStart;
  61. }
  62. private const int LookupCount = 100;
  63. [Benchmark]
  64. public void FindPreResource()
  65. {
  66. for (int i = 0; i < LookupCount; ++i)
  67. {
  68. _searchStart.FindResource("preTheme");
  69. }
  70. }
  71. [Benchmark]
  72. public void FindPostResource()
  73. {
  74. for (int i = 0; i < LookupCount; ++i)
  75. {
  76. _searchStart.FindResource("postTheme");
  77. }
  78. }
  79. [Benchmark]
  80. public void FindNotExistingResource()
  81. {
  82. for (int i = 0; i < LookupCount; ++i)
  83. {
  84. _searchStart.FindResource("notPresent");
  85. }
  86. }
  87. }
  88. }