Skip to content

Commit d29f6a1

Browse files
EvangelinkCopilot
andauthored
[efficiency-improver] perf: cache newline+color string in SimpleAnsiTerminal (#8834)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 494227e commit d29f6a1

1 file changed

Lines changed: 6 additions & 1 deletion

File tree

src/Platform/Microsoft.Testing.Platform/OutputDevice/Terminal/SimpleAnsiTerminal.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ namespace Microsoft.Testing.Platform.OutputDevice.Terminal;
1212
internal sealed class SimpleAnsiTerminal : SimpleTerminal
1313
{
1414
private string? _foregroundColor;
15+
// Cached concatenation of "\n" + _foregroundColor, computed once in SetColor to avoid
16+
// re-allocating the same string on every Append/AppendLine call when a color is active.
17+
private string? _newlineAndColor;
1518
private bool _prependColor;
1619

1720
public SimpleAnsiTerminal(IConsole console)
@@ -49,6 +52,7 @@ public override void SetColor(TerminalColor color)
4952
{
5053
string setColor = $"{AnsiCodes.CSI}{(int)color}{AnsiCodes.SetColor}";
5154
_foregroundColor = setColor;
55+
_newlineAndColor = "\n" + setColor;
5256
Console.Write(setColor);
5357
// This call set the color for current line, no need to prepend on next write.
5458
_prependColor = false;
@@ -57,10 +61,11 @@ public override void SetColor(TerminalColor color)
5761
public override void ResetColor()
5862
{
5963
_foregroundColor = null;
64+
_newlineAndColor = null;
6065
_prependColor = false;
6166
Console.Write(AnsiCodes.SetDefaultColor);
6267
}
6368

6469
private string? SetColorPerLine(string value)
65-
=> _foregroundColor == null ? value : value.Replace("\n", $"\n{_foregroundColor}");
70+
=> _newlineAndColor == null ? value : value.Replace("\n", _newlineAndColor);
6671
}

0 commit comments

Comments
 (0)