A Dictionary as a Simple Result Cache

A cache reuses results for equivalent calls. The chosen key has to capture every input that changes the result.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace repeated work
  2. Check an omitted dependency
  3. Build the key from every answer-changing input
  4. Choose when a saved result is still valid

Trace repeated work

A reusable calculator can store the result for a particular length and width. Inputs 3 and 8 yield 24 and can be served again from the same key. Pure functions are natural candidates because their results depend on supplied values.

Check an omitted dependency

A fee based on both zone and year gives incorrect reuse if only the zone forms the key. A composite key can hold both. If underlying fee tables change independently, the cache also needs a version or invalidation boundary.[1]

Build the key from every answer-changing input

A formatting function can produce different output for the same amount under different locales. A cache keyed only by amount can return the previous locale's formatting. Include locale and any format policy in the key, or use a cache scoped to the locale explicitly. Test two different contexts with equal amounts, then repeat the first call and verify that it reuses the correct result. See composite dictionary keys.

Choose when a saved result is still valid

A cache for immutable arithmetic results can keep an entry as long as storage permits. A cache for a versioned catalogue needs an invalidation strategy when the underlying record changes. A failed lookup can have a different lifetime from a successful one. Test the same key before and after an update, including a record that did not exist initially. See negative cache results.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩