From 4204aa9441600e9bd1e8571c60cd7174c74ac124 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Wed, 18 Nov 2020 15:02:11 -0500 Subject: [PATCH] Avoid string.Split in LoggerRuleSelector.IsBetter (#44753) --- .../src/LoggerRuleSelector.cs | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Logging/src/LoggerRuleSelector.cs b/src/libraries/Microsoft.Extensions.Logging/src/LoggerRuleSelector.cs index 1f3aa5240668e..7ebce26bbfc35 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/LoggerRuleSelector.cs +++ b/src/libraries/Microsoft.Extensions.Logging/src/LoggerRuleSelector.cs @@ -7,8 +7,6 @@ namespace Microsoft.Extensions.Logging { internal class LoggerRuleSelector { - private static readonly char[] WildcardChar = { '*' }; - public void Select(LoggerFilterOptions options, Type providerType, string category, out LogLevel? minLevel, out Func filter) { filter = null; @@ -40,7 +38,6 @@ public void Select(LoggerFilterOptions options, Type providerType, string catego } } - private static bool IsBetter(LoggerFilterRule rule, LoggerFilterRule current, string logger, string category) { // Skip rules with inapplicable type or category @@ -49,19 +46,32 @@ private static bool IsBetter(LoggerFilterRule rule, LoggerFilterRule current, st return false; } - if (rule.CategoryName != null) + string categoryName = rule.CategoryName; + if (categoryName != null) { - string[] categoryParts = rule.CategoryName.Split(WildcardChar); - if (categoryParts.Length > 2) + const char WildcardChar = '*'; + + int wildcardIndex = categoryName.IndexOf(WildcardChar); + if (wildcardIndex != -1 && + categoryName.IndexOf(WildcardChar, wildcardIndex + 1) != -1) { throw new InvalidOperationException("Only one wildcard character is allowed in category name."); } - string prefix = categoryParts[0]; - string suffix = categoryParts.Length > 1 ? categoryParts[1] : string.Empty; + ReadOnlySpan prefix, suffix; + if (wildcardIndex == -1) + { + prefix = categoryName.AsSpan(); + suffix = default; + } + else + { + prefix = categoryName.AsSpan(0, wildcardIndex); + suffix = categoryName.AsSpan(wildcardIndex + 1); + } - if (!category.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || - !category.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) + if (!category.AsSpan().StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || + !category.AsSpan().EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) { return false; }