Are there any adverse effect to including library
/require
statements inside of functions that will be called very frequently?
The time used see
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