with_gc: Evaluate an expression and then collect garbage.

View source: R/prog_utils.R

with_gcR Documentation

Evaluate an expression and then collect garbage.

Description

Logically, this function is equivalent to identity(), simply returning the value of the expression passed to it. However, it also ensures that after evaluating this expression, a garbage collection run is performed, even if the expression throws an error.

Usage

with_gc(expr, ...)

Arguments

expr

The expression to evaluate.

...

Further arguments are passed to gc().

Details

I have found this function occasionally useful when dealing with very large objects that bump up against the memory capacity of the computer I am using. One common use case is loading a very large R data file and keeping only one object from it while discarding the rest. However, overuse of this function when it is not needed will simply slow down your code.

See Also

gc()

Examples


with_gc({
  # Create a "large" object (this one is not actually large because
  # examples need to be kept small)
  large_object <- 1:5000
  # Return only a small piece of the object.
  large_object[5]
})
# large_object has now been garbage-collected


DarwinAwardWinner/rctutils documentation built on July 22, 2022, 5:19 a.m.