Søren Højsgaard
2010-Sep-08 12:31 UTC
[R] Extracting elements from list: Is [[ always faster than $ ??
Dear list It seems to me that extracting elements from a list using '[[' is somewhat faster than using '$'. For example:> x <- as.list(1:25) > names(x) <- letters[1:length(x)] > dput(x)structure(list(a = 1L, b = 2L, c = 3L, d = 4L, e = 5L, f = 6L, g = 7L, h = 8L, i = 9L, j = 10L, k = 11L, l = 12L, m = 13L, n = 14L, o = 15L, p = 16L, q = 17L, r = 18L, s = 19L, t = 20L, u = 21L, v = 22L, w = 23L, x = 24L, y = 25L), .Names = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"))> > system.time({ for (ii in 1:1000000) x[[21]] })user system elapsed 0.55 0.00 0.54> system.time({ for (ii in 1:1000000) x[["u"]]})user system elapsed 0.84 0.00 0.84> system.time({ for (ii in 1:1000000) x$u})user system elapsed 1.12 0.00 1.13 Does anyone know if this is always the case? (I have not found anything about speed in this connection on the help pages, apologies if I have overlooked something). I use R.2.11.1 on Windows 7. Regards
Uwe Ligges
2010-Sep-13 13:23 UTC
[R] Extracting elements from list: Is [[ always faster than $ ??
Yes: "$"() has to calculate more on matching the names --- and is more of a hack anyway. Although, I would not worry to much about 0.3 seconds in 1000000 evaluations ... Uwe On 08.09.2010 14:31, S?ren H?jsgaard wrote:> Dear list > > It seems to me that extracting elements from a list using '[[' is somewhat faster than using '$'. For example: > >> x<- as.list(1:25) >> names(x)<- letters[1:length(x)] >> dput(x) > structure(list(a = 1L, b = 2L, c = 3L, d = 4L, e = 5L, f = 6L, > g = 7L, h = 8L, i = 9L, j = 10L, k = 11L, l = 12L, m = 13L, > n = 14L, o = 15L, p = 16L, q = 17L, r = 18L, s = 19L, t = 20L, > u = 21L, v = 22L, w = 23L, x = 24L, y = 25L), .Names = c("a", > "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", > "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y")) >> >> system.time({ for (ii in 1:1000000) x[[21]] }) > user system elapsed > 0.55 0.00 0.54 >> system.time({ for (ii in 1:1000000) x[["u"]]}) > user system elapsed > 0.84 0.00 0.84 >> system.time({ for (ii in 1:1000000) x$u}) > user system elapsed > 1.12 0.00 1.13 > Does anyone know if this is always the case? (I have not found anything about speed in this connection on the help pages, apologies if I have overlooked something). > > I use R.2.11.1 on Windows 7. > > Regards > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.