High-performance cache policies and supporting data structures.
Feature: policy-random
Evict a uniformly random resident entry when capacity is reached.
Select victims randomly with equal probability:
Random eviction provides a baseline for comparing smarter policies.
In cachekit, src/policy/random.rs uses:
HashMap<K, (usize, V)> mapping key to (index in vec, value)Vec<K> dense array of keys for O(1) random accessget(key)insert(key, value)key exists: update value in placei = rand() % lenvictim = keys[i]keys[i] with keys[last]Example:
keys = [A, B, C, D]
Random picks index 1 (B)
Swap B with D: [A, D, C, B]
Update D's index to 1
Pop: [A, D, C]
Remove B from HashMap
Random provides worst-case performance bounds:
Any policy with access pattern awareness should beat Random on workloads with locality.
| Policy | Tracks Access | Overhead | Hit Rate (with locality) |
|---|---|---|---|
| Random | No | Minimal | Baseline (worst) |
| FIFO | Insertion | Low | Better |
| LRU | Recency | Medium | Much better |
| LFU | Frequency | Medium | Much better |
The O(1) eviction uses swap-remove:
Vec<K> provides O(1) random access(index, value) to track positionAlternative (simpler but O(n)):
cachekit uses the O(1) approach for best performance.