oldmoe / lruhash

A simple hash with a limited element count, LRU elements will be removed to make room for new ones.

This URL has Read+Write access

oldmoe (author)
Sat Apr 11 09:30:48 -0700 2009
name age message
file README Loading commit data...
directory lib/
file lruhash.gemspec
README
LRUHash

This is a hash class that closely mimicks the original Ruby hash with a subtle difference. It is limited in size and 
cannot grow beyond a max value. This is done by maintaining the hashed objects in activity order (both insertion and 
access activities) and removing the least recently used item if the hash exceeds its size limit. 

Pros 

Useful for implementing in-process caches where memory growth control is desired

Cons

Currently you can only control the number of entries in the Hash as opposed to the memory it uses. Providing an 
estimation of object memory consumption will make the insertion process a lot slower (except if we limit the values to 
something like strings). That's why I decided I can live with this limitation though.

Example

myhash = LRUHash.new
myhash.max = 2

myhash[1] = 1
myhash[2] = 2

myhash.length # => 2

myhash[3] = 3

myhash.length # => 2

myhash[1] # => nil