Version 0 of most-recently-used

Updated 2015-01-25 01:23:39 by pooryorick

One caching strategy is to retain the X most-recently-referenced items and discard any additional items. In "high performance" MRU-list ... , comp.lang.tcl, 2015-01-21, Christian Gollwitzer suggests an implementation of most-recently used that takes advantage of the order-preserving operation of dicts. Here is the suggestion, slightly modified to be more general:

proc pushmru {name limit args} {
    upvar $name dict
    foreach key $args {
        dict unset dict $key 
        dict set dict $key {}
        while {[dict size $dict] > $limit} {
            dict unset dict [lindex [dict keys $dict] 0]
        }
    }
    return $dict
}

Example

set i 0
while {[incr i] < 20} {
    pushmru cache 4 key$i
}