From 1660c8ca1b6b20d95a6432d289b66aa4c5cfab59 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Dec 2023 19:24:16 +0100 Subject: [PATCH] Optimize HlslDefinitionsSyntaxProcessor.GetDeclaredTypes --- .../HlslDefinitionsSyntaxProcessor.cs | 35 ++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 98dd60fe..22919a98 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; @@ -100,17 +99,35 @@ internal static class HlslDefinitionsSyntaxProcessor VariableDeclarator(Identifier(mappedName!))))); } - // Declare the methods of the current type - foreach (KeyValuePair method in instanceMethods.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type))) + // Enumerate all members in a single pass, so we can avoid materializing the collection. + // Additionally, this lets us add all members to the struct declaration in a single go. + static IEnumerable GatherInstanceMethods( + INamedTypeSymbol type, + IReadOnlyDictionary instanceMethods, + IReadOnlyDictionary constructors) { - structDeclaration = structDeclaration.AddMembers(method.Value); + // Normal instance methods + foreach (KeyValuePair method in instanceMethods) + { + if (SymbolEqualityComparer.Default.Equals(method.Key.ContainingType, type)) + { + yield return method.Value; + } + } + + // Constructors and stubs + foreach (KeyValuePair methods in constructors) + { + if (SymbolEqualityComparer.Default.Equals(methods.Key.ContainingType, type)) + { + yield return methods.Value.Stub; + yield return methods.Value.Ctor; + } + } } - // Also do the same for all constructors - foreach (KeyValuePair methods in constructors.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type))) - { - structDeclaration = structDeclaration.AddMembers(methods.Value.Stub, methods.Value.Ctor); - } + // Declare the methods of the current type + structDeclaration = structDeclaration.WithMembers(structDeclaration.Members.AddRange(GatherInstanceMethods(type, instanceMethods, constructors))); // Insert the trailing ; right after the closing bracket (after normalization) builder.Add((