% Generated by tinyroxygen: do not edit by hand
% Please edit documentation in cache.R
\name{mcache}
\alias{mcache}
\title{Create a Memory Cache}
\usage{
mcache(
  max_size = Inf,
  max_age = Inf,
  max_n = Inf,
  evict = c("lru", "fifo"),
  missing = key_missing()
)
}

\arguments{
\item{max_size}{Maximum size of the cache, in bytes, as reported by
  \code{\link[utils]{object.size}}. Use \code{Inf} (the default) for no
  limit.}

\item{max_age}{Maximum age of an object, in seconds, before it is evicted.
  Use \code{Inf} (the default) for no limit.}

\item{max_n}{Maximum number of objects allowed in the cache. Use
  \code{Inf} (the default) for no limit.}

\item{evict}{Eviction policy used when \code{max_n} or \code{max_size} is
  exceeded: \code{"lru"} (least recently used, the default) or
  \code{"fifo"} (first in, first out).}

\item{missing}{Value returned by \code{get()} when \code{key} is not
  present in the cache. Defaults to a \code{\link{key_missing}}()
  sentinel; test for it with \code{\link{is.key_missing}}().}
}

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

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

\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
}

