cache_exec {xfun}R Documentation

Cache the execution of an expression in memory or on disk

Description

Caching is based on the assumption that if the input does not change, the output will not change. After an expression is executed for the first time, its result will be saved (either in memory or on disk). The next run will be skipped and the previously saved result will be loaded directly if all external inputs of the expression remain the same, otherwise the cache will be invalidated and the expression will be re-executed.

Usage

cache_exec(expr, path = "cache/", id = NULL, ...)

Arguments

expr

An R expression to be cached.

path

The path to save the cache. The special value ":memory:" means in-memory caching. If it is intended to be a directory path, please make sure to add a trailing slash.

id

A stable and unique string identifier for the expression to be used to identify a unique copy of cache for the current expression from all cache files (or in-memory elements). If not provided, an MD5 digest of the deparsed expression will be used, which means if the expression does not change (changes in comments or white spaces do not matter), the id will remain the same. This may not be a good default is two identical expressions are cached under the same path, because they could overwrite each other's cache when one expression's cache is invalidated, which may or may not be what you want. If you do not want that to happen, you need to manually provide an id.

...

More arguments to control the behavior of caching (see ‘Details’).

Details

Arguments supported in ... include:

Value

If the cache is found, the cached value of the expression will be loaded and returned (other local variables will also be lazy-loaded into the current environment as a side-effect). If cache does not exist, the expression is executed and its value is returned.

Examples

# the first run takes about 1 second
y1 = xfun::cache_exec({
    x = rnorm(1e+05)
    Sys.sleep(1)
    x
}, path = ":memory:", id = "sim-norm")

# the second run takes almost no time
y2 = xfun::cache_exec({
    # comments won't affect caching
    x = rnorm(1e+05)
    Sys.sleep(1)
    x
}, path = ":memory:", id = "sim-norm")

# y1, y2, and x should be identical
stopifnot(identical(y1, y2), identical(y1, x))

[Package xfun version 0.46 Index]