From 24012bfb21da7c8abcc86c97c0609aad4e3df381 Mon Sep 17 00:00:00 2001 From: Morilli <35152647+Morilli@users.noreply.github.com> Date: Sat, 28 Sep 2024 17:28:50 +0200 Subject: [PATCH] optimize TasLagLog.RemoveFrom - closes #4058 --- .../movie/tasproj/TasLagLog.cs | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs b/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs index 9e784ead9b..d92b40d325 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.IO; -using System.Linq; using BizHawk.Common.CollectionExtensions; @@ -10,8 +9,8 @@ namespace BizHawk.Client.Common { public class TasLagLog { - private Dictionary _lagLog = new Dictionary(); - private Dictionary _wasLag = new Dictionary(); + private SortedList _lagLog = new(); + private Dictionary _wasLag = new(); public bool? this[int frame] { @@ -41,13 +40,19 @@ namespace BizHawk.Client.Common public bool RemoveFrom(int frame) { - var frames = _lagLog.Keys.Where(k => k > frame).ToList(); - foreach (var f in frames) + // find the index of the first lag log entry with frame number > `frame` + int startIndex = _lagLog.Keys.LowerBoundBinarySearch(static key => key, frame) + 1; + if (startIndex >= _lagLog.Count) return false; + + // iterate in reverse to prevent array copies in RemoveAt + for (int i = _lagLog.Count - 1; i >= startIndex; i--) { - RemoveLagEntry(f); + int frameNumber = _lagLog.Keys[i]; + _wasLag[frameNumber] = _lagLog.Values[i]; + _lagLog.RemoveAt(i); } - return frames.Any(); + return true; } public void RemoveHistoryAt(int frame) @@ -69,7 +74,7 @@ namespace BizHawk.Client.Common public void Load(TextReader tr) { - _lagLog = JsonConvert.DeserializeObject>(tr.ReadLine()); + _lagLog = JsonConvert.DeserializeObject>(tr.ReadLine()); _wasLag = JsonConvert.DeserializeObject>(tr.ReadLine()); } @@ -86,7 +91,7 @@ namespace BizHawk.Client.Common public void FromLagLog(TasLagLog log) { - _lagLog = log._lagLog.ToDictionary(); + _lagLog = new SortedList(log._lagLog); _wasLag = log._wasLag.ToDictionary(); }