From ca10f049e5a41318a5d19580a8abf9d01003ee6e Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Tue, 21 Aug 2018 10:27:25 -0400 Subject: [PATCH] perf: IcdOrderedDictionary maintains a collection of values ordered by key --- .../Collections/IcdOrderedDictionary.cs | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/ICD.Common.Utils/Collections/IcdOrderedDictionary.cs b/ICD.Common.Utils/Collections/IcdOrderedDictionary.cs index 5c3474b..586ccd6 100644 --- a/ICD.Common.Utils/Collections/IcdOrderedDictionary.cs +++ b/ICD.Common.Utils/Collections/IcdOrderedDictionary.cs @@ -9,6 +9,7 @@ namespace ICD.Common.Utils.Collections public sealed class IcdOrderedDictionary : IDictionary { private readonly List m_OrderedKeys; + private readonly List m_ValuesOrderedByKey; private readonly Dictionary m_Dictionary; private readonly IComparer m_Comparer; @@ -20,14 +21,7 @@ namespace ICD.Common.Utils.Collections public ICollection Keys { get { return m_OrderedKeys; } } - public ICollection Values - { - get - { - return m_OrderedKeys.Select(k => m_Dictionary[k]) - .ToArray(m_OrderedKeys.Count); - } - } + public ICollection Values { get { return m_ValuesOrderedByKey; } } public TValue this[TKey key] { @@ -39,7 +33,10 @@ namespace ICD.Common.Utils.Collections throw new ArgumentNullException("key"); if (!ContainsKey(key)) - m_OrderedKeys.AddSorted(key, m_Comparer); + { + int index = m_OrderedKeys.AddSorted(key, m_Comparer); + m_ValuesOrderedByKey.Insert(index, value); + } m_Dictionary[key] = value; } @@ -79,6 +76,7 @@ namespace ICD.Common.Utils.Collections m_Comparer = comparer; m_OrderedKeys = new List(); + m_ValuesOrderedByKey = new List(); m_Dictionary = new Dictionary(equalityComparer); } @@ -105,6 +103,7 @@ namespace ICD.Common.Utils.Collections public void Clear() { m_OrderedKeys.Clear(); + m_ValuesOrderedByKey.Clear(); m_Dictionary.Clear(); } @@ -122,7 +121,10 @@ namespace ICD.Common.Utils.Collections if (!m_Dictionary.Remove(key)) return false; - m_OrderedKeys.Remove(key); + int index = m_OrderedKeys.BinarySearch(key, m_Comparer); + + m_OrderedKeys.RemoveAt(index); + m_ValuesOrderedByKey.RemoveAt(index); return true; }