From d782a064621de7c7042c185d26ce7ba71e4d37a6 Mon Sep 17 00:00:00 2001 From: Todd Grunke Date: Wed, 13 May 2020 16:00:34 -0700 Subject: [PATCH] Decrease allocations from using method groups (dotnet/aspnetcore-tooling#1896) * Previous optimization didn't help as much as intended. By specifying a method group as the arguments to method like ReadWhile, an allocation was still occurring. Instead, cache the Func as a member in the class and use it instead of the method group.\n\nCommit migrated from https://github.com/dotnet/aspnetcore-tooling/commit/2e6aa150bc201c6381ccabfffd97e8361bb317e9 --- .../src/Legacy/CSharpCodeParser.cs | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs index f3b6e22919..7339e9149f 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs @@ -16,6 +16,27 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy '@', '!', '<', '/', '?', '[', '>', ']', '=', '"', '\'', '*' }); + // Following four high traffic methods cached as using method groups would cause allocation on every invocation. + protected static readonly Func IsSpacingToken = (token) => + { + return token.Kind == SyntaxKind.Whitespace; + }; + + protected static readonly Func IsSpacingTokenIncludingNewLines = (token) => + { + return IsSpacingToken(token) || token.Kind == SyntaxKind.NewLine; + }; + + protected static readonly Func IsSpacingTokenIncludingComments = (token) => + { + return IsSpacingToken(token) || token.Kind == SyntaxKind.CSharpComment; + }; + + protected static readonly Func IsSpacingTokenIncludingNewLinesAndComments = (token) => + { + return IsSpacingTokenIncludingNewLines(token) || token.Kind == SyntaxKind.CSharpComment; + }; + private static readonly Func IsValidStatementSpacingToken = IsSpacingTokenIncludingNewLinesAndComments; @@ -2622,26 +2643,6 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy result.Value == keyword; } - protected static bool IsSpacingToken(SyntaxToken token) - { - return token.Kind == SyntaxKind.Whitespace; - } - - protected static bool IsSpacingTokenIncludingNewLines(SyntaxToken token) - { - return IsSpacingToken(token) || token.Kind == SyntaxKind.NewLine; - } - - protected static bool IsSpacingTokenIncludingComments(SyntaxToken token) - { - return IsSpacingToken(token) || token.Kind == SyntaxKind.CSharpComment; - } - - protected static bool IsSpacingTokenIncludingNewLinesAndComments(SyntaxToken token) - { - return IsSpacingTokenIncludingNewLines(token) || token.Kind == SyntaxKind.CSharpComment; - } - protected class Block { public Block(string name, SourceLocation start)