15

在将非常频繁地调用的函数中包含library/语句是否有任何不利影响?require

使用的时间似乎可以忽略不计,但我每隔几分钟就调用一次函数,我想知道重复require调用是否有任何缺点?
请注意,该功能只是个人实用程序,不会被共享。即,我是唯一使用它的人

顺便说一句,任何关于为什么library慢一半的见解require?我的印象是它们是同义词。

  WithREQUIRE <- function(x) {
    require(stringr)
    str_detect(x, "hello")
  }

  WithLIBRARY <- function(x) {
    library(stringr)
    str_detect(x, "hello")
  }

  Without <- function(x) {
    str_detect(x, "hello")
  }

  x <- "goodbye"

  library(rbenchmark)
  benchmark(WithREQUIRE(x), WithLIBRARY(X), Without(x), replications=1e3, order="relative")

  #            test replications elapsed relative user.self sys.self
  #      Without(x)         1000   0.592    1.000     0.262    0.006
  #  WithREQUIRE(x)         1000   0.650    1.098     0.295    0.015
  #  WithLIBRARY(X)         1000   1.359    2.296     0.572    0.024
4

1 回答 1

12

require检查包是否已经加载(在搜索路径上)

使用

loaded <- paste("package", package, sep = ":") %in% search()

并且只有在这样的情况下才会继续加载它FALSE

library包括一个类似的测试,但当它是 TRUE 时会做更多的stuff事情(包括创建可用包的列表。

require继续使用tryCatch 对 library 的调用并将创建一条 message 。

因此,单个调用libraryrequire当一个包不在搜索路径上时可能会导致library更快

system.time(require(ggplot2))
## Loading required package: ggplot2
##   user  system elapsed 
##   0.08    0.00    0.47 
detach(package:ggplot2)
system.time(library(ggplot2))
##   user  system elapsed 
##   0.06    0.01    0.08

但是,如果包已经加载,那么正如您所展示的那样,require它会更快,因为它除了检查包是否已加载之外没有做更多的事情。

最好的解决方案是创建一个导入的小包stringr(或至少str_extract从 stringr

于 2013-03-06T22:06:44.457 回答