From 6fa68ba2a38c98ae2da5f1eba18f4e00e72c9218 Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Wed, 4 Oct 2023 18:18:48 +0200 Subject: [PATCH] Improve performance of `PublishOutput` method --- .../LogicGates/Interfaces/LogicGate.cs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/StoneRed.LogicSimulator/Simulation/LogicGates/Interfaces/LogicGate.cs b/StoneRed.LogicSimulator/Simulation/LogicGates/Interfaces/LogicGate.cs index 1a63acc..c9bc947 100644 --- a/StoneRed.LogicSimulator/Simulation/LogicGates/Interfaces/LogicGate.cs +++ b/StoneRed.LogicSimulator/Simulation/LogicGates/Interfaces/LogicGate.cs @@ -11,10 +11,12 @@ namespace StoneRed.LogicSimulator.Simulation.LogicGates.Interfaces; internal abstract class LogicGate { private readonly List logicGateConnections = new(); + private bool logicGateConnectionsChnaged = false; private int currentInput; private int newInput; private int output; private int cachedOutput; + private LogicGateConnection[] logicGateConnectionsArray = Array.Empty(); public IReadOnlyList LogicGateConnections => logicGateConnections.AsReadOnly(); public abstract int OutputCount { get; set; } public abstract int InputCount { get; set; } @@ -70,6 +72,7 @@ internal abstract class LogicGate lock (logicGateConnections) { logicGateConnections.Add(new LogicGateConnection(logicGate, inputIndex, outputIndex)); + logicGateConnectionsChnaged = true; } } @@ -93,6 +96,7 @@ internal abstract class LogicGate (!inputIndex.HasValue || c.InputIndex == inputIndex) && (!outputIndex.HasValue || c.OutputIndex == outputIndex)); logicGateConnections.RemoveAt(index); + logicGateConnectionsChnaged = true; } } @@ -145,13 +149,20 @@ internal abstract class LogicGate private void PublishOutput() { - lock (logicGateConnections) + if (logicGateConnectionsChnaged) { - foreach (LogicGateConnection connection in logicGateConnections) + lock (logicGateConnections) { - connection.LogicGate.SetInput(output.GetBit(connection.OutputIndex), connection.InputIndex); + logicGateConnectionsArray = logicGateConnections.ToArray(); + logicGateConnectionsChnaged = false; } } + + for (int i = 0; i < logicGateConnectionsArray.Length; i++) + { + LogicGateConnection connection = logicGateConnectionsArray[i]; + connection.LogicGate.SetInput(output.GetBit(connection.OutputIndex), connection.InputIndex); + } } }