在非常频繁调用的函数内包含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
Run Code Online (Sandbox Code Playgroud)
mne*_*nel 12
require 检查包是否已加载(在搜索路径上)
运用
loaded <- paste("package", package, sep = ":") %in% search()
Run Code Online (Sandbox Code Playgroud)
如果是这样的话,只会加载它 FALSE
library包括一个类似的测试,但是stuff当它为TRUE时会更多(包括创建可用包列表).
require继续使用tryCatch 对库的调用并将创建一条消息.
因此,单个调用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
Run Code Online (Sandbox Code Playgroud)
但是,如果软件包已经加载,那么就像你展示的那样,require速度更快,因为它不会检查包装是否加载.
最好的解决方案是创建一个导入的小包stringr(或至少str_extract从stringr