Learn R Programming

yulab.utils (version 0.2.3)

initial_cache: Cache intermediate data

Description

Utilities to cache intermediate data: initialize items, update items, remove items, and retrieve elements.

Usage

initial_cache()

get_cache()

rm_cache()

initial_cache_item(item)

get_cache_item(item)

rm_cache_item(item)

update_cache_item(item, elements, ttl = NULL)

get_cache_element(item, elements, default = NULL, prune_expired = TRUE)

prune_cache_item(item)

cache_list_items()

cache_size()

cache_save(path)

cache_load(path)

with_cache(item, key, compute, ttl = NULL)

Value

Cache environment, item, or selected elements

Arguments

item

Cache item name

elements

Elements to cache

ttl

Time-to-live in seconds

default

Default value if cache element is missing

prune_expired

Logical, whether to prune expired items

path

File path to save or load cache

key

Element key

compute

Function to compute value when missing

Examples

Run this code
if (FALSE) {
 slow_fib <- function(x) {
     if (x < 2) return(1)
     slow_fib(x-2) + slow_fib(x-1)
 }
 
 fast_fib <- function(x) {
     if (x < 2) return(1)
     res <- get_cache_element('fibonacci', as.character(x))
     if (!is.null(res)) {
         return(res)
     }
     res <- fast_fib(x-2) + fast_fib(x-1)
     e <- list()
     e[[as.character(x)]] <- res
     update_cache_item('fibonacci', e)
     return(res)
 }

 system.time(slow_fib(30))
 system.time(fast_fib(30)) 
    
 }

Run the code above in your browser using DataLab