Allow arbitrary "costs" per value inserted #160
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I wouldn't suggest merging this as-is, but its a possibly useful extension I made to LRU for myself, so I thought it might be useful to contribute it back.
The idea is that in some cases I want to limit the cache size not by the number of cache entries, but by some other metric, e.g. number of bytes. This is because that data that I have has a very long tail, in which some values to cache will be extremely large (100s of MBs), so if I were to set a cache size of e.g. 1024 I could easily eat up all my memory. But the large values only occur occasionally, so usually I would like to have a fairly large number of cache entries.
My solution is to add a method,
put_with_cost
that allows the caller to submit an arbitraryusize
"cost" for the key-value pair, and entries from the cache are evicted only when the sum of all cost values exceeds the cost capacity of the cache. So if you were to always pass a cost of 1, that would be the exact same behavior as before. None of this changes the eviction order (still LRU), just the limit at which we have to start evicting.Let me know if this is something that makes sense here, or not. Thanks!