6

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
Michele
  • 8,563
  • 6
  • 45
  • 72
  • 5
    someone needed to point out: these are microseconds! Likely insignificant if your code is going to do anything more complex. – flodel Aug 02 '13 at 10:12
  • @flodel in 99.9% you are right. But I've got a program that has lots of function calls, all rapped in a big loop. I'm about to roll out a new version completely vectorised, thanks to data.table, but it's still in dev mode, so in the meantime a millisecond saved in each cycle of the loop is minutes less in the whole program... – Michele Aug 02 '13 at 11:19
  • 1
    If you have name conflicts and that's why you need `::`, you could do `my.unique <- base::unique.default` and use `my.unique`. – Roland Aug 02 '13 at 11:22

1 Answers1

9

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.

Roland
  • 127,288
  • 10
  • 191
  • 288