Skip to content

Instantly share code, notes, and snippets.

@TobCap
Last active December 21, 2015 05:18
Show Gist options
  • Select an option

  • Save TobCap/6255804 to your computer and use it in GitHub Desktop.

Select an option

Save TobCap/6255804 to your computer and use it in GitHub Desktop.
creating a function is very costly
library(microbenchmark)
microbenchmark(
do.call = do.call("function", list(as.pairlist(alist(x=)), NULL)),
eval = eval(call("function", as.pairlist(alist(x=)), NULL)),
as.function = as.function(alist(x = , NULL)),
as.function.default = as.function.default(alist(x = , NULL)),
"function(x) NULL" = function(x) NULL
)
# Unit: nanoseconds
# expr min lq median uq max neval
# do.call 33880 35217 35663 36109.0 166723 100
# eval 35217 36554 37000 37446.0 46808 100
# as.function 46362 47700 48591 49259.5 91831 100
# as.function.default 28530 29868 29868 30759.0 41458 100
# function(x) NULL 0 1 446 447.0 4012 100
args_ <- as.pairlist(alist(x=))
body_ <- NULL
argbody1 <- list(args_, NULL)
argbody2 <- alist(x=, NULL)
microbenchmark(
do.call = do.call("function", argbody1),
eval = eval(call("function", args_, body_)),
as.function = as.function(argbody2),
as.function.default = as.function.default(argbody2),
"function(x) NULL" = function(x) NULL
)
# Unit: nanoseconds
# expr min lq median uq max neval
# do.call 5350 5796 6242 6688 20060 100
# eval 6687 7579 8470 8917 22290 100
# as.function 23627 24964 25410 26302 107880 100
# as.function.default 3567 4013 4013 4459 41904 100
# function(x) NULL 0 446 446 447 2676 100
args_ <- as.pairlist(alist(x=))
body_ <- 100
argbody1 <- list(args_, body_)
argbody2 <- c(args_, if (is.null(body_)) list(NULL) else body_)
microbenchmark(
do.call = do.call("function", argbody1),
eval = eval(call("function", args_, body_)),
as.function = as.function(argbody2),
as.function.default = as.function.default(argbody2),
"function(x) 100" = function(x) 100
)
# Unit: nanoseconds
# expr min lq median uq max neval
# do.call 5350 5796 6242.0 6688 18278 100
# eval 7133 7579 8470.0 8916 2655064 100
# as.function 23181 24519 25410.0 25856 111892 100
# as.function.default 3567 4013 4235.5 4459 5796 100
# function(x) 100 0 446 447.0 447 2230 100
f1. <- function(..., env = parent.frame()){
d <- as.pairlist(as.vector(substitute((...)), "list")[-1])
n <- length(d)
eval(call("function", as.formals(d[-n]), d[[n]]), env)
}
f2. <- function(..., env = parent.frame()){
d <- as.vector(substitute((...)), "list")[-1]
if (length(d) == 0) as.function.default(list(call("{")), env)
else if (length(d) == 1) as.function.default(d, env)
else as.function.default(c(as.formals(d[-length(d)]), d[[length(d)]]), env)
}
f1.(x, y, x+y)
f2.(x, y, x+y)
# > identical(f1.(x, y, x+y), f2.(x, y, x+y), ignore.environment=TRUE, ignore.bytecode=TRUE)
# [1] TRUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment