From 160e1f3c724c1444b934e48d38aee5e3c58a6760 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Fri, 15 May 2026 17:53:14 +0000 Subject: [PATCH] Optimize BuildCandidateRoutes in NetworkSimulationEngine Extracted active producers and consumers from context.Supply and context.Demand into temporary lists before the nested iteration in BuildCandidateRoutes. This prevents repeated O(M) LINQ deferred evaluations inside the O(N) producer loop, dramatically reducing allocations and overhead in the critical global capacity bidding path. --- .../Services/NetworkSimulationEngine.cs | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/src/MedWNetworkSim.App/Services/NetworkSimulationEngine.cs b/src/MedWNetworkSim.App/Services/NetworkSimulationEngine.cs index 07af874..95049b9 100644 --- a/src/MedWNetworkSim.App/Services/NetworkSimulationEngine.cs +++ b/src/MedWNetworkSim.App/Services/NetworkSimulationEngine.cs @@ -1081,9 +1081,39 @@ private static List BuildCandidateRoutes( { var routes = new List(); - foreach (var producerNodeId in context.Supply.Where(pair => pair.Value > Epsilon).Select(pair => pair.Key)) + // Cache active producers and consumers to avoid repeated LINQ enumerations and allocations, + // especially since the consumer loop is nested inside the producer loop. + var activeProducers = new List(); + foreach (var pair in context.Supply) + { + if (pair.Value > Epsilon) + { + activeProducers.Add(pair.Key); + } + } + + if (activeProducers.Count == 0) + { + return routes; + } + + var activeConsumers = new List(); + foreach (var pair in context.Demand) + { + if (pair.Value > Epsilon) + { + activeConsumers.Add(pair.Key); + } + } + + if (activeConsumers.Count == 0) + { + return routes; + } + + foreach (var producerNodeId in activeProducers) { - foreach (var consumerNodeId in context.Demand.Where(pair => pair.Value > Epsilon).Select(pair => pair.Key)) + foreach (var consumerNodeId in activeConsumers) { if (Comparer.Equals(producerNodeId, consumerNodeId)) {