From 485924edd2b7395d67ed5e3344daa70612769d54 Mon Sep 17 00:00:00 2001 From: Todd Grunke Date: Mon, 11 May 2020 10:27:40 -0700 Subject: [PATCH] Improve Annotation and SpanContext performance. (dotnet/aspnetcore-tooling#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 https://github.com/dotnet/aspnetcore-tooling/commit/a060f129ff01176eb30b20379e951e05fedbc7a4 --- .../src/Legacy/LegacySyntaxNodeExtensions.cs | 28 +++++++++++++------ .../src/Syntax/SyntaxNodeExtensions.cs | 5 ++++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/LegacySyntaxNodeExtensions.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/LegacySyntaxNodeExtensions.cs index 95152d53a8..46bcd01003 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/LegacySyntaxNodeExtensions.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/LegacySyntaxNodeExtensions.cs @@ -67,17 +67,29 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy var newAnnotation = new SyntaxAnnotation(SyntaxConstants.SpanContextKind, spanContext); - var newAnnotations = new List(); - newAnnotations.Add(newAnnotation); - foreach (var annotation in node.GetAnnotations()) - { - if (annotation.Kind != newAnnotation.Kind) - { - newAnnotations.Add(annotation); + List newAnnotations = null; + if (node.ContainsAnnotations) + { + var existingNodeAnnotations = node.GetAnnotations(); + for (int i = 0; i < existingNodeAnnotations.Length; i++) + { + var annotation = existingNodeAnnotations[i]; + if (annotation.Kind != newAnnotation.Kind) + { + if (newAnnotations == null) + { + newAnnotations = new List(); + newAnnotations.Add(newAnnotation); + } + + newAnnotations.Add(annotation); + } } } + + var newAnnotationsArray = newAnnotations == null ? new[] { newAnnotation } : newAnnotations.ToArray(); - return node.WithAnnotations(newAnnotations.ToArray()); + return node.WithAnnotations(newAnnotationsArray); } public static SyntaxNode LocateOwner(this SyntaxNode node, SourceChange change) diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxNodeExtensions.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxNodeExtensions.cs index 677c06d894..ae0973cfff 100644 --- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxNodeExtensions.cs +++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxNodeExtensions.cs @@ -28,6 +28,11 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax throw new ArgumentNullException(nameof(node)); } + if (!node.ContainsAnnotations) + { + return null; + } + var annotation = node.GetAnnotations().FirstOrDefault(n => n.Kind == key); return annotation?.Data; }