Cache Objects in Disk or Memory

Reuse objects with a long processing time either by storing those in disk or memory. Uses caching to identify R objects (e.g., data frames, plots, etc.) and allows repeated access to those. Created with the specific goal of skipping the waiting time for summary tables obtained from large 'SQL' tables. It is extensible to other uses, such as caching plots in 'Tabler' dashboards to reduce waiting times.


tinycache

This R package offers a minimal approach to cache R objects. It is offers similar functions to rlang::hash(), cachem::cache_mem(), and cachem::cache_disk().

The usage is quite elemental. While this package was create to cache summary tables obtained from large 'SQL' tables, it works with arbitrary R objects, such as linear models.

Here is an example of how to cache results for an lm() output:

library(tinycache)

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
}

cache <- dcache(dir = tempdir())
fit_model(5e7, cache) # computed and cached
fit_model(5e7, cache) # reused from disk, no recomputation

cache <- mcache()
fit_model(5e7, cache) # computed and cached
fit_model(5e7, cache) # reused from memory, no recomputation

How to check that it works:

cache <- mcache()

# 1st run
system.time(fit_model(5e7, cache))

# > system.time(fit_model(5e7, cache))
#    user  system elapsed 
#  10.088   1.289   8.278

# 2nd run
system.time(fit_model(5e7, cache))

# > system.time(fit_model(5e7, cache))
#    user  system elapsed 
#   0.000   0.000   0.001

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.

install.packages("tinycache")

0.1 by Mauricio Vargas Sepulveda, 2 months ago


https://pacha.dev/tinycache/


Report a bug at https://github.com/pachadotdev/tinycache/issues


Browse source code at https://github.com/cran/tinycache


Authors: Mauricio Vargas Sepulveda [aut, cre] (ORCID:


Documentation:   PDF Manual  


Apache License 2.0 license


Imports utils

Suggests tinytest

Linking to cpp4r


See at CRAN