From 3ad21fecc2dbc979e6bdace63c15b2aa7f102601 Mon Sep 17 00:00:00 2001 From: Deukhoofd Date: Fri, 24 Apr 2020 18:24:51 +0200 Subject: [PATCH] Performance improvements for getting random value from libraries. --- src/Library/BaseLibrary.hpp | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/Library/BaseLibrary.hpp b/src/Library/BaseLibrary.hpp index dc6786f..a07028c 100644 --- a/src/Library/BaseLibrary.hpp +++ b/src/Library/BaseLibrary.hpp @@ -3,18 +3,19 @@ #include #include +#include #include #include #include #include -#include namespace CreatureLib::Library { template class BaseLibrary { Arbutils::Collections::Dictionary _values; + Arbutils::Collections::List _listValues; public: - BaseLibrary(size_t initialCapacity = 32) : _values(initialCapacity) {} + BaseLibrary(size_t initialCapacity = 32) : _values(initialCapacity), _listValues(initialCapacity) {} virtual ~BaseLibrary() { for (const auto& v : _values) { @@ -26,14 +27,24 @@ namespace CreatureLib::Library { inline void Insert(const Arbutils::CaseInsensitiveConstString& key, const T* value) { AssertNotNull(value) _values.Insert(key.GetHash(), value); + _listValues.Append(key); } inline void Insert(uint32_t hashedKey, const T* value) { AssertNotNull(value) _values.Insert(hashedKey, value); + _listValues.Append(hashedKey); } - inline void Delete(const Arbutils::CaseInsensitiveConstString& key) { _values.erase(key.GetHash()); } - inline void Delete(uint32_t hashedKey) { _values.Remove(hashedKey); } + inline void Delete(const Arbutils::CaseInsensitiveConstString& key) { + _values.erase(key.GetHash()); + auto k = _listValues.IndexOf(key); + _listValues.Remove(k); + } + inline void Delete(uint32_t hashedKey) { + _values.Remove(hashedKey); + auto k = _listValues.IndexOf(hashedKey); + _listValues.Remove(k); + } bool TryGet(const Arbutils::CaseInsensitiveConstString& name, const T*& out) const { return TryGet(name.GetHash(), out); @@ -56,14 +67,12 @@ namespace CreatureLib::Library { [[nodiscard]] size_t GetCount() const { return _values.Count(); } inline const T* GetRandomValue(Arbutils::Random rand = Arbutils::Random()) const { - auto i = rand.Get(_values.Count()); - auto& map = _values.GetStdMap(); - return std::next(std::begin(map), i)->second; + auto i = rand.Get(_listValues.Count()); + return _values[_listValues[i]]; } inline const T* GetRandomValue(Arbutils::Random* rand) const { - auto i = rand->Get(_values.Count()); - auto& map = _values.GetStdMap(); - return std::next(std::begin(map), i)->second; + auto i = rand->Get(_listValues.Count()); + return _values[_listValues[i]]; } }; }