Skip to content

Commit 485924e

Browse files
authored
Improve Annotation and SpanContext performance. (dotnet/razor#1881)
The razor perf test shows about 70 ms CPU of WithSpanContext is in allocation. GetAnnotation similarly is showing about 60 ms in allocation (of which this only partly improves)\n\nCommit migrated from dotnet/razor@a060f12
1 parent d1e7d8e commit 485924e

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

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

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,17 +67,29 @@ public static TNode WithSpanContext<TNode>(this TNode node, SpanContext spanCont
6767

6868
var newAnnotation = new SyntaxAnnotation(SyntaxConstants.SpanContextKind, spanContext);
6969

70-
var newAnnotations = new List<SyntaxAnnotation>();
71-
newAnnotations.Add(newAnnotation);
72-
foreach (var annotation in node.GetAnnotations())
73-
{
74-
if (annotation.Kind != newAnnotation.Kind)
75-
{
76-
newAnnotations.Add(annotation);
70+
List<SyntaxAnnotation> newAnnotations = null;
71+
if (node.ContainsAnnotations)
72+
{
73+
var existingNodeAnnotations = node.GetAnnotations();
74+
for (int i = 0; i < existingNodeAnnotations.Length; i++)
75+
{
76+
var annotation = existingNodeAnnotations[i];
77+
if (annotation.Kind != newAnnotation.Kind)
78+
{
79+
if (newAnnotations == null)
80+
{
81+
newAnnotations = new List<SyntaxAnnotation>();
82+
newAnnotations.Add(newAnnotation);
83+
}
84+
85+
newAnnotations.Add(annotation);
86+
}
7787
}
7888
}
89+
90+
var newAnnotationsArray = newAnnotations == null ? new[] { newAnnotation } : newAnnotations.ToArray();
7991

80-
return node.WithAnnotations(newAnnotations.ToArray());
92+
return node.WithAnnotations(newAnnotationsArray);
8193
}
8294

8395
public static SyntaxNode LocateOwner(this SyntaxNode node, SourceChange change)

src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxNodeExtensions.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ public static object GetAnnotationValue<TNode>(this TNode node, string key) wher
2828
throw new ArgumentNullException(nameof(node));
2929
}
3030

31+
if (!node.ContainsAnnotations)
32+
{
33+
return null;
34+
}
35+
3136
var annotation = node.GetAnnotations().FirstOrDefault(n => n.Kind == key);
3237
return annotation?.Data;
3338
}

0 commit comments

Comments
 (0)