performance - R: Why is the [[ ]] approach for subsetting a list faster than using $? -


i've been working on few projects have required me lot of list subsetting , while profiling code realised object[["namehere"]] approach subsetting lists faster object$namehere approach.

as example if create list named components:

a.long.list <- as.list(rep(1:1000)) names(a.long.list) <- paste0("something",1:1000) 

why this:

system.time ( (i in 1:10000) {     a.long.list[["something997"]] } )   user  system elapsed  0.15    0.00    0.16  

faster this:

system.time (     (i in 1:10000) {         a.long.list$something997     } )  user  system elapsed  0.23    0.00    0.23  

my question whether behaviour true universally , should avoid $ subset wherever possible or efficient choice depend on other factors?

function [[ first goes through elements trying exact match, then tries partial match. $ function tries both exact , partial match on each element in turn. if execute:

system.time (     (i in 1:10000) {      a.long.list[["something9973", exact=false]]      } ) 

i.e., running partial match there no exact match, find $ in fact ever faster.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -