Version 0 of Result caching

Updated 2002-07-19 07:53:04

Richard Suchenwirth 2002-07-19 - If you repeatedly do the same time-consuming calculations (e.g. string similarity), it may be a good idea to keep the previous results in a cache and, for every call of the same command after the result, just return the cached value.

This implementation uses an array in caller's scope (he might make it global, or not) whose name is explicitly given. This way, you could have multiple caches in parallel, and selectively reset some when needed.

 proc cached {cacheName command} {
    upvar 1 $cacheName cache
    if {![info exists cache($command)]} {
        set cache($command) [uplevel 1 $command]
    } else {
        set cache($command)
    }
 }

# testing:

 % time {cached c {stringSimilarity "Tool Command Language" "Tool Command Languages"}}
 422000 microseconds per iteration
 % time {cached c {stringSimilarity "Tool Command Language" "Tool Command Languages"}}
 0 microseconds per iteration

The second calls saves you more than 0.4 seconds... Note however that caching results makes only sense if the command always returns the same value - caching commands like

 gets $fp
 expr rand()
 clock seconds

is certainly a bad idea...


Category Concept | Arts and crafts of Tcl-Tk programming