Skip to content

Commit bd00e2b

Browse files
authored
perf: Optimize CountWordInText (#10050)
* use SearchValues for special chars lookup on NET 8 * only allocate delimiter chars once * ensure no closure allocations with static lambdas
1 parent a6c4b21 commit bd00e2b

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

src/Docfx.Build/Conceptual/WordCounter.cs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@ internal static class WordCounter
99
{
1010
private static readonly string[] ExcludeNodeXPaths = ["//title"];
1111

12+
#if NET8_0_OR_GREATER
13+
private static readonly System.Buffers.SearchValues<char> SpecialChars = System.Buffers.SearchValues.Create(".?!;:,()[]");
14+
#else
15+
private static readonly string SpecialChars = ".?!;:,()[]";
16+
#endif
17+
18+
private static readonly char[] DelimiterChars = [' ', '\t', '\n'];
19+
1220
public static long CountWord(string html)
1321
{
1422
ArgumentNullException.ThrowIfNull(html);
@@ -50,10 +58,7 @@ private static int CountWordInText(string text)
5058
return 0;
5159
}
5260

53-
string specialChars = ".?!;:,()[]";
54-
char[] delimiterChars = [' ', '\t', '\n'];
55-
56-
string[] wordList = text.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
57-
return wordList.Count(s => !s.Trim().All(specialChars.Contains));
61+
string[] wordList = text.Split(DelimiterChars, StringSplitOptions.RemoveEmptyEntries);
62+
return wordList.Count(static s => !s.Trim().All(static c => SpecialChars.Contains(c)));
5863
}
5964
}

0 commit comments

Comments
 (0)