如果已经加载了函数,则在函数中需要一个软件包有什么影响? [英] Whats the impact of requiring a package inside a function if the package is already loaded?

查看:75
本文介绍了如果已经加载了函数,则在函数中需要一个软件包有什么影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在经常调用的函数中包含library/require语句是否有不利影响?

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

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

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

顺便说一句,关于为什么library的速度是require的一半的任何见解?我印象中他们是同义词.

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

推荐答案

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

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

使用

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

,并且只有在FALSE

library包括一个类似的测试,但当stuff为TRUE时,它会做更多的工作(包括创建可用软件包的列表.

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

require使用对库的tryCatch调用继续,并将创建一条消息.

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

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

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

但是,如果已经加载了软件包,那么正如您所显示的,require速度更快,因为它所做的只是检查软件包是否已加载.

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.

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

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

这篇关于如果已经加载了函数,则在函数中需要一个软件包有什么影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆