Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why calling a function specifying the namespace is slower?

I thought that specifying the namespace I gave R less work to do, but I'm probably wrong

library(microbenchmark)
> microbenchmark(unique.default(c(1,1:10)),base::unique.default(c(1,1:10)))
Unit: microseconds
                             expr    min     lq  median     uq    max neval
       unique.default(c(1, 1:10))  3.528  3.849  4.0095  4.170 12.509   100
 base::unique.default(c(1, 1:10)) 11.546 12.188 12.5090 12.829 59.012   100
like image 385
Michele Avatar asked Aug 02 '13 09:08

Michele


1 Answers

The first gets the function from the package environment that is created when base is attached:

> "unique.default" %in% ls("package:base")
[1] TRUE

The second uses function :: to get the function from the package namespace:

> `::`
function (pkg, name) 
{
    pkg <- as.character(substitute(pkg))
    name <- as.character(substitute(name))
    getExportedValue(pkg, name)
} 

Look how many function calls this needs.

If you need a function only once it might be more efficient to get it from the namespace. But if you need it repeatedly or need several function from a package, you should attach the package.

like image 155
Roland Avatar answered Oct 14 '22 19:10

Roland