VisualTreeTraversal.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Avalonia.Controls;
  5. using Avalonia.UnitTests;
  6. using Avalonia.VisualTree;
  7. using BenchmarkDotNet.Attributes;
  8. namespace Avalonia.Benchmarks.Traversal
  9. {
  10. [MemoryDiagnoser]
  11. public class VisualTreeTraversal
  12. {
  13. private readonly TestRoot _root;
  14. private readonly List<Control> _controls = new List<Control>();
  15. private readonly List<Control> _shuffledControls;
  16. public VisualTreeTraversal()
  17. {
  18. var panel = new StackPanel();
  19. _root = new TestRoot { Child = panel, Renderer = new NullRenderer()};
  20. _controls.Add(panel);
  21. _controls = ControlHierarchyCreator.CreateChildren(_controls, panel, 3, 5, 4);
  22. var random = new Random(1);
  23. _shuffledControls = _controls.OrderBy(r => random.Next()).ToList();
  24. _root.LayoutManager.ExecuteInitialLayoutPass(_root);
  25. }
  26. [Benchmark]
  27. public void FindAncestorOfType_Linq()
  28. {
  29. foreach (Control control in _controls)
  30. {
  31. control.GetSelfAndVisualAncestors()
  32. .OfType<TestRoot>()
  33. .FirstOrDefault();
  34. }
  35. }
  36. [Benchmark]
  37. public void FindAncestorOfType_Optimized()
  38. {
  39. foreach (Control control in _controls)
  40. {
  41. control.FindAncestorOfType<TestRoot>();
  42. }
  43. }
  44. [Benchmark]
  45. public void FindCommonVisualAncestor()
  46. {
  47. foreach (IVisual first in _controls)
  48. {
  49. foreach (Control second in _shuffledControls)
  50. {
  51. first.FindCommonVisualAncestor(second);
  52. }
  53. }
  54. }
  55. }
  56. }