Skip to content

Instantly share code, notes, and snippets.

@lukego
Last active December 12, 2015 03:19
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukego/4706097 to your computer and use it in GitHub Desktop.
Save lukego/4706097 to your computer and use it in GitHub Desktop.
Table data structure that "garbage collects" not-recently-used items in O(1) time

I use this data structure all the time. Can someone leave a comment and tell me what it's called?

  1. insert(k,v): add a new value
  2. lookup(k): lookup an existing value
  3. age(): delete old entries (that have not been used since previous call to age())
# Initialize 'old' and 'new' to empty tables
local old, new = {}, {}

function insert(k, v)
  new[k] = v
end

function lookup(k)
  if new[k] then
    # Found in new table
    return new[k]
  elseif old[k] then
    # Migrate from old table to new table
    new[k] = old[k]
    return old[k]
  else
    # Not found
    return nil
  end
end

function age()
  # Entries in 'old' are dropped, entries in 'new' become old.
  old = new
  new = {} # empty table
end
@philipaconrad
Copy link

It looks like an LRU cache that has no hard limit on the number of elements.

Also, I ported this data structure to Python recently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment