Skip to content

Commit d782a06

Browse files
authored
Decrease allocations from using method groups (dotnet/razor#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 dotnet/razor@2e6aa15
1 parent 016fd1e commit d782a06

File tree

1 file changed

+21
-20
lines changed

1 file changed

+21
-20
lines changed

src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,27 @@ internal class CSharpCodeParser : TokenizerBackedParser<CSharpTokenizer>
1616
'@', '!', '<', '/', '?', '[', '>', ']', '=', '"', '\'', '*'
1717
});
1818

19+
// Following four high traffic methods cached as using method groups would cause allocation on every invocation.
20+
protected static readonly Func<SyntaxToken, bool> IsSpacingToken = (token) =>
21+
{
22+
return token.Kind == SyntaxKind.Whitespace;
23+
};
24+
25+
protected static readonly Func<SyntaxToken, bool> IsSpacingTokenIncludingNewLines = (token) =>
26+
{
27+
return IsSpacingToken(token) || token.Kind == SyntaxKind.NewLine;
28+
};
29+
30+
protected static readonly Func<SyntaxToken, bool> IsSpacingTokenIncludingComments = (token) =>
31+
{
32+
return IsSpacingToken(token) || token.Kind == SyntaxKind.CSharpComment;
33+
};
34+
35+
protected static readonly Func<SyntaxToken, bool> IsSpacingTokenIncludingNewLinesAndComments = (token) =>
36+
{
37+
return IsSpacingTokenIncludingNewLines(token) || token.Kind == SyntaxKind.CSharpComment;
38+
};
39+
1940
private static readonly Func<SyntaxToken, bool> IsValidStatementSpacingToken =
2041
IsSpacingTokenIncludingNewLinesAndComments;
2142

@@ -2622,26 +2643,6 @@ protected internal bool At(CSharpKeyword keyword)
26222643
result.Value == keyword;
26232644
}
26242645

2625-
protected static bool IsSpacingToken(SyntaxToken token)
2626-
{
2627-
return token.Kind == SyntaxKind.Whitespace;
2628-
}
2629-
2630-
protected static bool IsSpacingTokenIncludingNewLines(SyntaxToken token)
2631-
{
2632-
return IsSpacingToken(token) || token.Kind == SyntaxKind.NewLine;
2633-
}
2634-
2635-
protected static bool IsSpacingTokenIncludingComments(SyntaxToken token)
2636-
{
2637-
return IsSpacingToken(token) || token.Kind == SyntaxKind.CSharpComment;
2638-
}
2639-
2640-
protected static bool IsSpacingTokenIncludingNewLinesAndComments(SyntaxToken token)
2641-
{
2642-
return IsSpacingTokenIncludingNewLines(token) || token.Kind == SyntaxKind.CSharpComment;
2643-
}
2644-
26452646
protected class Block
26462647
{
26472648
public Block(string name, SourceLocation start)

0 commit comments

Comments
 (0)