Files
Sourcetrail/src/lib/utility/OrderedCache.h
T
mlangkabel 1a9d736f28 src: improved cache implementation
* use const ref in cache
* improved performance of FilePath caching in FileRegister
2017-12-21 13:35:41 +01:00

46 lines
1.0 KiB
C++

#ifndef ORDERED_CACHE_H
#define ORDERED_CACHE_H
#include <functional>
#include <map>
template <typename KeyType, typename ValType>
class OrderedCache
{
public:
OrderedCache(std::function<ValType(const KeyType&)> calculator);
ValType getValue(const KeyType& key);
private:
std::function<ValType(const KeyType&)> m_calculator;
std::map<KeyType, ValType> m_map;
size_t m_hitCount;
size_t m_missCount;
};
template <typename KeyType, typename ValType>
OrderedCache<KeyType, ValType>::OrderedCache(std::function<ValType(const KeyType&)> calculator)
: m_calculator(calculator)
, m_hitCount(0)
, m_missCount(0)
{
}
template <typename KeyType, typename ValType>
ValType OrderedCache<KeyType, ValType>::getValue(const KeyType& key)
{
typename std::map<KeyType, ValType>::const_iterator it = m_map.find(key);
if (it != m_map.end())
{
++m_hitCount;
return it->second;
}
++m_missCount;
ValType val = m_calculator(key);
m_map.insert(std::pair<KeyType, ValType>(key, val));
return val;
}
#endif // ORDERED_CACHE_H