|
| 1 | +using System.Text; |
| 2 | +using BenchmarkDotNet.Attributes; |
| 3 | +using Tui = Terminal.Gui; |
| 4 | + |
| 5 | +namespace Terminal.Gui.Benchmarks.Text.RuneExtensions; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Benchmarks for <see cref="Tui.RuneExtensions.Encode"/> performance fine-tuning. |
| 9 | +/// </summary> |
| 10 | +[MemoryDiagnoser] |
| 11 | +[BenchmarkCategory (nameof (Tui.RuneExtensions))] |
| 12 | +public class Encode |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Benchmark for previous implementation. |
| 16 | + /// </summary> |
| 17 | + [Benchmark] |
| 18 | + [ArgumentsSource (nameof (DataSource))] |
| 19 | + public byte [] Previous (Rune rune, byte [] destination, int start, int count) |
| 20 | + { |
| 21 | + _ = StringEncodingGetBytes (rune, destination, start, count); |
| 22 | + return destination; |
| 23 | + } |
| 24 | + |
| 25 | + /// <summary> |
| 26 | + /// Benchmark for current implementation. |
| 27 | + /// |
| 28 | + /// Avoids intermediate heap allocations with stack allocated intermediate buffer. |
| 29 | + /// </summary> |
| 30 | + [Benchmark (Baseline = true)] |
| 31 | + [ArgumentsSource (nameof (DataSource))] |
| 32 | + public byte [] Current (Rune rune, byte [] destination, int start, int count) |
| 33 | + { |
| 34 | + _ = Tui.RuneExtensions.Encode (rune, destination, start, count); |
| 35 | + return destination; |
| 36 | + } |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Previous implementation with intermediate byte array and string allocation. |
| 40 | + /// </summary> |
| 41 | + private static int StringEncodingGetBytes (Rune rune, byte [] dest, int start = 0, int count = -1) |
| 42 | + { |
| 43 | + byte [] bytes = Encoding.UTF8.GetBytes (rune.ToString ()); |
| 44 | + var length = 0; |
| 45 | + |
| 46 | + for (var i = 0; i < (count == -1 ? bytes.Length : count); i++) |
| 47 | + { |
| 48 | + if (bytes [i] == 0) |
| 49 | + { |
| 50 | + break; |
| 51 | + } |
| 52 | + |
| 53 | + dest [start + i] = bytes [i]; |
| 54 | + length++; |
| 55 | + } |
| 56 | + |
| 57 | + return length; |
| 58 | + } |
| 59 | + |
| 60 | + public static IEnumerable<object []> DataSource () |
| 61 | + { |
| 62 | + Rune[] runes = [ new Rune ('a'),"𝔞".EnumerateRunes().Single() ]; |
| 63 | + |
| 64 | + foreach (var rune in runes) |
| 65 | + { |
| 66 | + yield return new object [] { rune, new byte [16], 0, -1 }; |
| 67 | + yield return new object [] { rune, new byte [16], 8, -1 }; |
| 68 | + // Does not work in original implementation |
| 69 | + //yield return new object [] { rune, new byte [16], 8, 8 }; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments