DirectPropertyBenchmark.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Runtime.CompilerServices;
  2. using BenchmarkDotNet.Attributes;
  3. namespace Avalonia.Benchmarks.Base
  4. {
  5. [MemoryDiagnoser]
  6. public class DirectPropertyBenchmark
  7. {
  8. private DirectClass _target = new();
  9. public DirectPropertyBenchmark()
  10. {
  11. RuntimeHelpers.RunClassConstructor(typeof(DirectClass).TypeHandle);
  12. }
  13. [Benchmark(Baseline = true)]
  14. public void SetAndRaiseOriginal()
  15. {
  16. var obj = _target;
  17. for (var i = 0; i < 100; ++i)
  18. {
  19. obj.IntValue += 1;
  20. }
  21. }
  22. [Benchmark]
  23. public void SetAndRaiseSimple()
  24. {
  25. var obj = _target;
  26. for (var i = 0; i < 100; ++i)
  27. {
  28. obj.IntValueSimple += 1;
  29. }
  30. }
  31. class DirectClass : AvaloniaObject
  32. {
  33. private int _intValue;
  34. public static readonly DirectProperty<DirectClass, int> IntValueProperty =
  35. AvaloniaProperty.RegisterDirect<DirectClass, int>(nameof(IntValue),
  36. o => o.IntValue,
  37. (o, v) => o.IntValue = v);
  38. public int IntValue
  39. {
  40. get => _intValue;
  41. set => SetAndRaise(IntValueProperty, ref _intValue, value);
  42. }
  43. public int IntValueSimple
  44. {
  45. get => _intValue;
  46. set
  47. {
  48. VerifyAccess();
  49. if (_intValue == value)
  50. {
  51. return;
  52. }
  53. var old = _intValue;
  54. _intValue = value;
  55. RaisePropertyChanged(IntValueProperty, old, _intValue);
  56. }
  57. }
  58. }
  59. }
  60. }