LruCache<K, V> class
Simple LRU cache.
TODO(chirayu): - add docs - add tests - should stringify keys?
class LruCache<K, V> extends Cache<K, V> { Map<K, V> _entries = new LinkedHashMap<K, V>(); int _capacity; int _hits = 0; int _misses = 0; LruCache({int capacity}) { this._capacity = (capacity == null) ? 0 : capacity; } V get(K key) { V value = _entries[key]; if (value != null || _entries.containsKey(key)) { ++_hits; // refresh _entries.remove(key); _entries[key] = value; } else { ++_misses; } return value; } V put(K key, V value) { // idempotent. needed to refresh an existing key. _entries.remove(key); // _capacity always > 0 but might not be true in some future. if (_capacity > 0 && _capacity == _entries.length) { // drop oldest entry when at capacity // _entries.keys.first is fairly cheap - 2 new calls. _entries.remove(_entries.keys.first); } _entries[key] = value; return value; } V remove(K key) => _entries.remove(key); void removeAll() => _entries.clear(); int get capacity => _capacity; int get size => _entries.length; CacheStats stats() => new CacheStats(capacity, size, _hits, _misses); // Debugging helper. String toString() => "[$runtimeType: capacity=$capacity, size=$size, items=$_entries]"; }
Extends
Cache<K, V> > LruCache<K, V>
Subclasses
Constructors
new LruCache({int capacity}) #
Properties
final int capacity #
int get capacity => _capacity;
final int size #
int get size => _entries.length;
Methods
V get(K key) #
Returns the value for key
from the cache. If key
is not in the cache,
returns null
.
V get(K key) { V value = _entries[key]; if (value != null || _entries.containsKey(key)) { ++_hits; // refresh _entries.remove(key); _entries[key] = value; } else { ++_misses; } return value; }
V put(K key, V value) #
Inserts/Updates the key
in the cache with value
and returns the value.
V put(K key, V value) { // idempotent. needed to refresh an existing key. _entries.remove(key); // _capacity always > 0 but might not be true in some future. if (_capacity > 0 && _capacity == _entries.length) { // drop oldest entry when at capacity // _entries.keys.first is fairly cheap - 2 new calls. _entries.remove(_entries.keys.first); } _entries[key] = value; return value; }
void removeAll() #
CacheStats stats() #
CacheStats stats() => new CacheStats(capacity, size, _hits, _misses);
String toString() #
Returns a string representation of this object.
docs inherited from Object
String toString() => "[$runtimeType: capacity=$capacity, size=$size, items=$_entries]";