Nested functions slower?

Is the definition of a child function that will be called by the parent function inside the parent element (as a nested function) slower?

For example, suppose solution 1:

Foo <- function(x) {

    Baz <- function(y) {
    #... do something
    }
    #... do something and call Baz, for instance
    sapply(x, Baz)
}

or alternatively solution 2:

Baz <- function(y) {
#... do something
}

Foo <- function(x) {

    #... do something and call Baz, for instance
    sapply(x, Baz)
}

In solution 1, there is an additional determination process Bazat startup Foo, so I assume that many of the calls Fooin solution 1 will be a bit slower. It's true?

+4
source share
1 answer

/, . , , . ,

m1<- function() {
    x<-rep(runif(100))
    Baz <- function(y) {
        mean(y)
    }
    sapply(x, Baz)
}

Baz <- function(y) {
        mean(y)
}
m2 <- function() {
    x<-rep(runif(100))
    sapply(x, Baz)
}

library(microbenchmark)
microbenchmark(m1(), m2())

, . . , , . " ", .

, . . .

+5

Source: https://habr.com/ru/post/1546767/


All Articles