Fundamentals - Garbage collection
- Because environment is attached to (enclosed by) function, temporary objects
don’t go away.
Cleaning up using rm()
inside a function:
f_dirty <- function(n) {
x <- runif(n)
m <- mean(x)
function() m
}
f_clean <- function(n) {
x <- runif(n)
m <- mean(x)
rm(x) # <---- Important part!
function() m
}
lobstr::obj_size(f_dirty(1e6))
#> 8.00 MB
lobstr::obj_size(f_clean(1e6))
#> 504 B