简体   繁体   English

在主 function 之外声明辅助函数是否更有效?

[英]Is it more efficient to declare helper functions outside the main function?

When I debug step by step this kind of function:当我逐步调试这种 function 时:

foo <- function(x) {
  helper <- function(x) x^2
  2 * helper(x)
}

I see that the helper function definition is evaluated each time.我看到每次都会评估助手 function 定义。 Is it the same, when no in debug mode?在调试模式下是否相同? Is it bad in terms of time execution?在时间执行方面是不是很糟糕?

You can try it yourself.你可以自己试试。 I didn't see much of a difference.我没有看到太大的不同。 inside or outside was faster on different runs when I tried it.当我尝试它时,内部或外部在不同的运行中更快。

library(microbenchmark)

foo1 <- function(x) {
  helper <- function(x) x^2
  2 * helper(x)
}

helper <- function(x) x^2
foo2 <- function(x) {
  2 * helper(x)
}

microbenchmark(
  inside = foo1(1:1000),
  outside = foo2(1:1000),
  times = 1000
)

Based on @John Coleman comment I have tried this:根据@John Coleman 的评论,我试过这个:

library(microbenchmark)

foo1 <- function(x) {
  helper <- function(x) {
    nested_helper <- function(y) {
      depper_helper <- function(z) {
        z + z
      }
      3 * depper_helper(y)
    }
    nested_helper(x) ^ 2
  }
  2 * helper(x)
}


nested_helper <- function(y) {
  3 * depper_helper(y)
}
depper_helper <- function(z) {
  z + z
}
helper <- function(x) {
  nested_helper(x) ^ 2
}
foo2 <- function(x) {
  2 * helper(x)
}

microbenchmark(
  inside = foo1(1:1000),
  outside = foo2(1:1000),
  times = 1000000
)

I ran it two times and obtain the same results:我运行了两次并获得了相同的结果:

Unit: microseconds
    expr min  lq     mean median  uq     max neval
  inside 5.0 5.4 8.822796    5.8 8.5 50905.9 1e+06
 outside 4.9 5.2 8.559778    5.6 8.3 47797.3 1e+06

Inside definition seems a little bit slower but not in a significant way.内部定义似乎有点慢,但不是很重要。 There must be some kind of optimization by the JIT compiler. JIT 编译器必须进行某种优化。 I would like confirmation of this.我想确认这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM