簡體   English   中英

在主 function 之外聲明輔助函數是否更有效?

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

當我逐步調試這種 function 時:

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

我看到每次都會評估助手 function 定義。 在調試模式下是否相同? 在時間執行方面是不是很糟糕?

你可以自己試試。 我沒有看到太大的不同。 當我嘗試它時,內部或外部在不同的運行中更快。

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
)

根據@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
)

我運行了兩次並獲得了相同的結果:

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

內部定義似乎有點慢,但不是很重要。 JIT 編譯器必須進行某種優化。 我想確認這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM