Whats the impact of requiring a package inside a function if the package is already loaded?

北慕城南 提交于 2019-12-09 08:21:54

问题


Are there any adverse effect to including library/require statements inside of functions that will be called very frequently?

The time used seems rather negligble, but I am calling the function every few minutes and I am wondering if there is any downside to the repetitve require calls?
note that the function is just a personal util and is not being shared. ie, I am the only one using it

Incidentally, any insight as to why library is half as slow as require? I was under the impression they were synonymous.

  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

回答1:


require checks whether the package is already loaded (on the search path)

using

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

and will only proceed with loading it if this is FALSE

library includes a similar test, but does a bit more stuff when this is TRUE (including creating a list of available packages.

require proceeds using a tryCatch call to library and will create a message .

So a single call to library or require when a package is not on the search path may result in library being faster

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

But, if the package is already loaded, then as you show, require is faster because it doesn't do much more than check the package is loaded.

The best solution would be to create a small package that imports stringr (or at least str_extract from stringr



来源:https://stackoverflow.com/questions/15258398/whats-the-impact-of-requiring-a-package-inside-a-function-if-the-package-is-alre

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!