mcache {tinycache}R Documentation

Create a Memory Cache

Description

A lightweight in-memory key-value cache. Values are stored directly in an environment (not serialized), so as long as an object is cached it will not be garbage collected.

Usage

mcache(
  max_size = Inf,
  max_age = Inf,
  max_n = Inf,
  evict = c("lru", "fifo"),
  missing = key_missing()
)

Arguments

max_size Maximum size of the cache, in bytes, as reported by object.size. Use Inf (the default) for no limit.
max_age Maximum age of an object, in seconds, before it is evicted. Use Inf (the default) for no limit.
max_n Maximum number of objects allowed in the cache. Use Inf (the default) for no limit.
evict Eviction policy used when max_n or max_size is exceeded: "lru" (least recently used, the default) or "fifo" (first in, first out).
missing Value returned by get() when key is not present in the cache. Defaults to a key_missing() sentinel; test for it with is.key_missing().

Value

An mcache object with methods get(key, missing), set(key, value), exists(key), remove(key), keys(), size(), reset(), and prune().

Examples

cache <- mcache()

fit_model <- function(n, cache) {
  key <- hash(n)
  cached <- cache$get(key)
  if (!is.key_missing(cached)) {
    return(cached)
  }

  set.seed(123)
  mydata <- data.frame(x = seq_len(n), y = seq_len(n) * 2 + rnorm(n))
  mycoef <- coef(lm(y ~ x, data = mydata))

  cache$set(key, mycoef)
  mycoef
}

fit_model(100, cache) # computed and cached
fit_model(100, cache) # reused from disk, no recomputation

Loading...