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

前端 未结 1 1874
余生分开走
余生分开走 2021-02-13 03:20

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

The time used see

相关标签:
1条回答
  • 2021-02-13 04:06

    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

    0 讨论(0)
提交回复
热议问题