I'm currently using C++17 and I'm looking for a way to implement an LRU cache, but have it be bounded by the size in bytes of the cache contents (e.g. 100MB) rather than the number of items the cache contains. I'm not concerned with a templatized, generic structure; it can be specific to the type.
I know how to make an LRU cache and bound it by size (e.g. see https://www.boost.org/doc/libs/1_70_0/boost/compute/detail/lru_cache.hpp), so the bounding by byte size, not the LRU algorithm itself, is the crux of the question.
Let's say I have a structure like this:
struct MyItem {
std::string some_id;
std::uint64 some_value;
std::map<std::uint32_t, MyOtherItem> some_map;
}
And I want to create an LRU cache with a basic interface like this (I'm using std::optional
as a placeholder for negative caching so I can store std::nullopt
for a key to cache the fact that I know it doesn't exist):
class LruCache {
LruCache(std::uint64_t max_size_bytes);
void Put(const std::string& key, const std::optional<MyItem> &entity);
std::optional<MyItem> Get(const std::string& key);
void Delete(const std::string& key);
}
The interface is not written in stone; I'm open to suggestions there too, but the parts that I'm most interested in are:
- At runtime (literally at cache put time), how do I know how big (in bytes) an instance of
MyItem
is? - How do I allocate the
max_size_bytes
cache limit? Do I allocate the cached block of memory up front and try to add/remove from that? Or do I keep a "total_bytes" counter class member that I just tick up and down as I add and remove items?
Thank you in advance for all of your suggestions!