[英]Whats the impact of requiring a package inside a function if the package is already loaded?
Are there any adverse effect to including library
/ require
statements inside of functions that will be called very frequently? 在非常频繁调用的函数中包含
library
/ 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? 使用的时间似乎相当可以忽略不计,但我每隔几分钟调用一次这个函数,我想知道重复
require
调用是否有任何缺点?
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
? 顺便说一下,任何关于为什么
library
速度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
checks whether the package is already loaded (on the search path) require
检查包是否已加载(在搜索路径上)
using 运用
loaded <- paste("package", package, sep = ":") %in% search()
and will only proceed with loading it if this is FALSE
如果这是
FALSE
话,它只会继续加载它
library
includes a similar test, but does a bit more stuff
when this is TRUE (including creating a list of available packages. library
包含一个类似的测试,但是当它为TRUE时会做更多的stuff
(包括创建可用包的列表)。
require
proceeds using a tryCatch
call to library and will create a message . require
使用tryCatch
调用库继续进行,并将创建一条消息。
So a single call to library
or require
when a package is not on the search path may result in library
being faster 因此,单个调用
library
或require
包不在搜索路径上时可能会导致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
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. 但是,如果软件包已经加载,那么在显示时,
require
会更快,因为它不会检查包加载的内容。
The best solution would be to create a small package that imports stringr
(or at least str_extract
from stringr 最好的解决办法是创建一个小的包,进口
stringr
(或至少str_extract
从stringr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.