From bb095dec37f6c8261bb43f106b3f1f5786464ccd Mon Sep 17 00:00:00 2001 From: Dimitar Krastev Date: Wed, 6 May 2026 19:46:14 +0300 Subject: [PATCH 1/2] Optimize LRUList when duplicate values are pushed. --- Common++/header/LRUList.h | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 002ea6721f..422b7ef6f1 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -43,33 +43,34 @@ namespace pcpp /// points to. int put(const T& element, T* deletedValue = nullptr) { - m_CacheItemsList.push_front(element); - - // Inserting a new element. If an element with an equivalent key already exists the method returns an - // iterator to the element that prevented the insertion - std::pair pair = - m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); - if (!pair.second) // already exists + // Try to insert a mapping to the new element. + // TODO: C++17: use try_emplace instead of emplace when we switch to C++17 + auto pair = m_CacheItemsMap.emplace(element, m_CacheItemsList.end()); + if (!pair.second) { - m_CacheItemsList.erase(pair.first->second); - pair.first->second = m_CacheItemsList.begin(); + // The element already exists. Move it to the head of the list. + m_CacheItemsList.splice(m_CacheItemsList.begin(), m_CacheItemsList, pair.first->second); + return 0; } + // The element is new. + m_CacheItemsList.push_front(element); + pair.first->second = m_CacheItemsList.begin(); + if (m_CacheItemsMap.size() > m_MaxSize) { - ListIterator lruIter = m_CacheItemsList.end(); - --lruIter; + auto const& item = m_CacheItemsList.back(); if (deletedValue != nullptr) { #if __cplusplus > 199711L || _MSC_VER >= 1800 - *deletedValue = std::move(*lruIter); + *deletedValue = std::move(item); #else - *deletedValue = *lruIter; + *deletedValue = item; #endif } - m_CacheItemsMap.erase(*lruIter); - m_CacheItemsList.erase(lruIter); + m_CacheItemsMap.erase(item); + m_CacheItemsList.pop_back(); return 1; } From 69be4a8556669161a1a7d3108e7b38c0a2507cca Mon Sep 17 00:00:00 2001 From: Dimitar Krastev Date: Wed, 6 May 2026 19:54:51 +0300 Subject: [PATCH 2/2] Fixup type. --- Common++/header/LRUList.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 422b7ef6f1..28ac6853b3 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -59,7 +59,7 @@ namespace pcpp if (m_CacheItemsMap.size() > m_MaxSize) { - auto const& item = m_CacheItemsList.back(); + auto& item = m_CacheItemsList.back(); if (deletedValue != nullptr) {