Reduce legacy Windows driver ANSI escape sequence intermediate string allocations (#3936)

* Skip WindowsConsole StringBuilder append ANSI escape sequence intermediate string allocations

Appending InterpolatedStringHandler directly to StringBuilder skips the formatting related intermediate string allocation. This should also be usable in other console implementation but currently I have no WSL etc. setup to actually verify correct functionality.

* Add CSI_Set* and CSI_Append* comparison benchmark

* Clean up CSI_SetVsAppend benchmark

* Change benchmark names to match the method group
This commit is contained in:
Tonttu
2025-03-01 18:36:31 +02:00
committed by GitHub
parent af9c6d7846
commit bc8bf380b2
4 changed files with 161 additions and 82 deletions

View File

@@ -0,0 +1,48 @@
using System.Text;
using BenchmarkDotNet.Attributes;
using Tui = Terminal.Gui;
namespace Terminal.Gui.Benchmarks.ConsoleDrivers.EscSeqUtils;
/// <summary>
/// Compares the Set and Append implementations in combination.
/// </summary>
/// <remarks>
/// A bit misleading because *CursorPosition is called very seldom compared to the other operations
/// but they are very similar in performance because they do very similar things.
/// </remarks>
[MemoryDiagnoser]
[BenchmarkCategory (nameof (Tui.EscSeqUtils))]
// Hide useless empty column from results.
[HideColumns ("stringBuilder")]
public class CSI_SetVsAppend
{
[Benchmark (Baseline = true)]
[ArgumentsSource (nameof (StringBuilderSource))]
public StringBuilder Set (StringBuilder stringBuilder)
{
stringBuilder.Append (Tui.EscSeqUtils.CSI_SetBackgroundColorRGB (1, 2, 3));
stringBuilder.Append (Tui.EscSeqUtils.CSI_SetForegroundColorRGB (3, 2, 1));
stringBuilder.Append (Tui.EscSeqUtils.CSI_SetCursorPosition (4, 2));
// Clear to prevent out of memory exception from consecutive iterations.
stringBuilder.Clear ();
return stringBuilder;
}
[Benchmark]
[ArgumentsSource (nameof (StringBuilderSource))]
public StringBuilder Append (StringBuilder stringBuilder)
{
Tui.EscSeqUtils.CSI_AppendBackgroundColorRGB (stringBuilder, 1, 2, 3);
Tui.EscSeqUtils.CSI_AppendForegroundColorRGB (stringBuilder, 3, 2, 1);
Tui.EscSeqUtils.CSI_AppendCursorPosition (stringBuilder, 4, 2);
// Clear to prevent out of memory exception from consecutive iterations.
stringBuilder.Clear ();
return stringBuilder;
}
public static IEnumerable<object> StringBuilderSource ()
{
return [new StringBuilder ()];
}
}