Yomguithereal / mnemonist

Curated collection of data structures for the JavaScript/TypeScript language.
https://yomguithereal.github.io/mnemonist
MIT License
2.24k stars 92 forks source link

Cache with time-to-keep expiry #191

Open mrflip opened 1 year ago

mrflip commented 1 year ago

This adds time-to-keep expiration to the LRUCacheWithDelete.

Besides the other ledgers of the backing cache, on every write operation the update time is saved in a fixed-sized array. No other speed or memory overhead is required for regular operations: most importantly, that means there is no age verification on read. Customer must periodically call the expire method, which evicts items older than the time-to-keep.

Our use case is a 15-minute time-to-keep on caches of 64k capacity, where we can tolerate a modest slop in expiration and small periodic expiry sweeps. The benchmark script demonstrates a 1M-element cache with a 10s ttk being expired every 2 seconds, spending 50-60ms on each expiry sweep. I don't know what use case would need those extremes but there you go.

Limitations:

Alternatives considered and discarded:

Potential Opportunities for improvement:

The commit history here is a hot mess that includes and crosses with the other PR on profiling. I'll reorganize with squashed commits once I button things up.