Last active
March 29, 2018 14:47
-
-
Save jimhester/3a30e54ff1e630e6965e243071c0619c to your computer and use it in GitHub Desktop.
getOption benchmark
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
getOptionOld <- function(x, default = NULL) { | |
## To avoid always performing the %in%, | |
## we use the original code if default is not specified. | |
## if(missing(default)) return(options(x)[[1L]]) | |
if(missing(default) || x %in% names(.Options)) | |
.Internal(getOption(x)) | |
else | |
default | |
} | |
getOptionNew <- function(x, default = NULL) { | |
ans <- .Internal(getOption(x)) | |
## not distinguishing an option that's NULL from a non-existing option | |
if(is.null(ans)) default else ans | |
} | |
bench <- microbenchmark::microbenchmark( | |
old_found = getOptionOld("width"), | |
old_missing = getOptionOld("blah"), | |
old_missing_default = getOptionOld("blah", "foo"), | |
new_found = getOptionNew("width"), | |
new_missing = getOptionNew("blah"), | |
new_missing_default = getOptionNew("blah", "foo") | |
) | |
bench | |
#> Unit: nanoseconds | |
#> expr min lq mean median uq max neval cld | |
#> old_found 406 450.0 536.53 493.0 570.0 925 100 a | |
#> old_missing 559 625.5 23613.27 707.0 829.5 2282638 100 a | |
#> old_missing_default 2138 2324.0 2507.76 2394.5 2517.0 8430 100 a | |
#> new_found 413 469.0 568.09 529.0 601.5 1588 100 a | |
#> new_missing 575 620.0 739.83 690.5 799.0 1416 100 a | |
#> new_missing_default 581 647.5 21285.04 746.5 865.5 2029400 100 a | |
# Would need to lookup a missing option with a default 1 million times before this | |
# would take more than 1 second. | |
system.time({ i <- 1; while((i <- i + 1) <= 1000000) getOptionOld("blah", "foo") }) | |
#> user system elapsed | |
#> 3.026 0.270 3.304 | |
# Created on 2018-03-29 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment