Update WordFilter.cs

Reduces startup alloc by 24KB if we don't allocate an array to store all regex strings
kinda small but ez free
This commit is contained in:
Kurt 2023-10-06 23:58:13 -07:00
parent bb5cc7cff1
commit fac682bcad

View File

@ -14,16 +14,19 @@ public static class WordFilter
/// Regex patterns to check against
/// </summary>
/// <remarks>No need to keep the original pattern strings around; the <see cref="Regex"/> object retrieves this via <see cref="Regex.ToString()"/></remarks>
private static readonly Regex[] Regexes = LoadPatterns(Util.GetStringList("badwords"));
private static readonly Regex[] Regexes = LoadPatterns(Util.GetStringResource("badwords")!);
// if you're running this as a server and don't mind a few extra seconds of startup, add RegexOptions.Compiled for slightly better checking.
private const RegexOptions Options = RegexOptions.CultureInvariant;
private static Regex[] LoadPatterns(IReadOnlyList<string> patterns)
private static Regex[] LoadPatterns(ReadOnlySpan<char> patterns)
{
var result = new Regex[patterns.Count];
for (int i = 0; i < patterns.Count; i++)
result[i] = new Regex(patterns[i], Options);
var lineCount = 1 + patterns.Count('\n');
var result = new Regex[lineCount];
var enumerator = patterns.EnumerateLines();
int i = 0;
while (enumerator.MoveNext())
result[i++] = new Regex(enumerator.Current.ToString(), Options);
return result;
}