From 9f2f1c575fd71c7dc67bf320e325c04086310147 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 16 Jul 2024 20:13:09 +1000 Subject: [PATCH] reduce alloc in ReplaceInvalidFileNameChars (#1244) --- src/Verify/FileNameCleaner.cs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/Verify/FileNameCleaner.cs b/src/Verify/FileNameCleaner.cs index ca39f5fc7d..69a3173ae3 100644 --- a/src/Verify/FileNameCleaner.cs +++ b/src/Verify/FileNameCleaner.cs @@ -60,20 +60,20 @@ public static string ReplaceInvalidFileNameChars(this string value) return value; } - var chars = value.ToCharArray(); - span[..index] - .CopyTo(chars); - chars[index] = '-'; + Span target = stackalloc char[value.Length]; + span.CopyTo(target); + + target[index] = '-'; index++; - for (; index < chars.Length; index++) + for (; index < target.Length; index++) { - if (IsInvalid(chars[index])) + if (IsInvalid(target[index])) { - chars[index] = '-'; + target[index] = '-'; } } - return new(chars); + return target.ToString(); } static int IndexOfInvalidChar(CharSpan span) => @@ -83,7 +83,6 @@ static int IndexOfInvalidChar(CharSpan span) => span.IndexOfAny(invalidFileNameChars.AsSpan()); #endif - static bool IsInvalid(char ch) => #if NET8_0_OR_GREATER invalidFileNameSearchValues.Contains(ch);