Ali
Ali

Reputation: 9840

Are nested functions slower?

Is defining a child function to be called by a parent function inside the parent (as a nested function) slower?

For instance 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 extra process of defining Baz while running Foo, so I guess many calls to Foo in solution 1 would be slightly slower. Is it true?

Upvotes: 4

Views: 1144

Answers (1)

MrFlick
MrFlick

Reputation: 206401

It's very hard to predict speed/efficiency without looking at particular functions and input data. What speeds up one type of process might not necessarily be good for another. You could try a simple benchmark like

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())

Here when i run it a bunch of times. Then seem very comparable. If you're trying to speed up code, this is unlikely to be a place where you are slowing down. But it's better to test "real world" scenarios just to be sure.

The importance of nesting functions really comes in when you create closures. A child function can access a parent function's environment. This can be a very powerful tool.

Upvotes: 5

Related Questions