Created
September 11, 2020 17:56
-
-
Save wch/31e986851826c8536862a74b13621fdb to your computer and use it in GitHub Desktop.
Memoize performance tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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