Skip to content

Instantly share code, notes, and snippets.

@wch
Created September 11, 2020 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/31e986851826c8536862a74b13621fdb to your computer and use it in GitHub Desktop.
Save wch/31e986851826c8536862a74b13621fdb to your computer and use it in GitHub Desktop.
Memoize performance tests
library(profvis)
library(microbenchmark)
library(memoise)
library(digest)
# Bare function
f <- function(a, b) {
a + b
}
# With memoise
g <- memoise(f)
# Manually memoized version
h <- local({
cache <- new.env(parent = emptyenv())
function(a, b) {
hash <- digest(list(a, b), algo = "xxhash64")
if (is.null(cache[[hash]])) {
res <- f(a, b)
cache[[hash]] <- res
}
cache[[hash]]
}
})
microbenchmark(
f(1, 100),
g(1, 100),
h(1, 100),
times = 1000
)
profvis({
for (i in 1:5000) {
f(1, 100)
}
for (i in 1:5000) {
g(1, 100)
}
for (i in 1:5000) {
h(1, 100)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment