IsSurrogatePair.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.Text;
  2. using BenchmarkDotNet.Attributes;
  3. using Tui = Terminal.Gui;
  4. namespace Terminal.Gui.Benchmarks.Text.RuneExtensions;
  5. /// <summary>
  6. /// Benchmarks for <see cref="Tui.RuneExtensions.IsSurrogatePair"/> performance fine-tuning.
  7. /// </summary>
  8. [MemoryDiagnoser]
  9. [BenchmarkCategory (nameof (Tui.RuneExtensions))]
  10. public class IsSurrogatePair
  11. {
  12. /// <summary>
  13. /// Benchmark for previous implementation.
  14. /// </summary>
  15. /// <param name="rune"></param>
  16. [Benchmark]
  17. [ArgumentsSource (nameof (DataSource))]
  18. public bool Previous (Rune rune)
  19. {
  20. return WithToString (rune);
  21. }
  22. /// <summary>
  23. /// Benchmark for current implementation.
  24. ///
  25. /// Avoids intermediate heap allocations by using stack allocated buffer.
  26. /// </summary>
  27. [Benchmark (Baseline = true)]
  28. [ArgumentsSource (nameof (DataSource))]
  29. public bool Current (Rune rune)
  30. {
  31. return Tui.RuneExtensions.IsSurrogatePair (rune);
  32. }
  33. /// <summary>
  34. /// Previous implementation with intermediate string allocation.
  35. /// </summary>
  36. private static bool WithToString (Rune rune)
  37. {
  38. return char.IsSurrogatePair (rune.ToString (), 0);
  39. }
  40. public static IEnumerable<object> DataSource ()
  41. {
  42. yield return new Rune ('a');
  43. yield return "𝔹".EnumerateRunes ().Single ();
  44. }
  45. }