dcache {tinycache}R Documentation

Create a Disk Cache

Description

A lightweight disk-backed key-value cache: each value is stored as its own .rds file inside dir. Pruning is not throttled, and eviction metadata (age, last-access time) comes directly from the files' own modification times rather than being tracked separately.

Usage

dcache(
  dir = NULL,
  max_size = Inf,
  max_age = Inf,
  max_n = Inf,
  evict = c("lru", "fifo"),
  missing = key_missing(),
  destroy_on_finalize = FALSE
)

Arguments

dir Directory used to store the cached files. If NULL (the default), a new temporary directory is created and used.
max_size, max_age, max_n, evict, missing See mcache.
destroy_on_finalize If TRUE, the cache directory and all of its contents are deleted from disk when the returned object is garbage collected. Default FALSE.

Value

A dcache object with the same methods as mcache, plus destroy(), which deletes the cache directory from disk.

Examples

cache <- dcache(dir = tempdir())

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...