Created
November 25, 2010 17:15
-
-
Save lgatto/715656 to your computer and use it in GitHub Desktop.
Comparing speed when populating an environment and a preallocated list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(MSnbase) | |
n <- 10000 | |
ll <- vector("list",length=n) | |
e <- new.env() | |
tl <- system.time(for (i in 1:n) | |
ll[[i]] <- new("Spectrum2")) | |
te <- system.time(for (i in 1:n) | |
assign(paste("X",i,sep=""),new("Spectrum2"),e)) | |
## Results for n=10000 | |
##> te | |
## user system elapsed | |
## 10.640 0.020 10.728 | |
##> tl | |
## user system elapsed | |
## 9.900 0.020 10.139 | |
## BUT -- A common problem is with subset-assign on list elements | |
## Thanks to Martin Morgan for this example | |
setClass("Lst", representation=representation(l="list")) | |
Lst <- function(l, ...) new("Lst", l=l, ...) | |
setClass("Env", representation=representation(e="environment")) | |
Env <- function(e, ...) new("Env", e=e, ...) | |
l <- replicate(5, matrix(0, 1e3, 1e3),simplify=FALSE) | |
names(l) <- letters[seq_len(length(l))] | |
lst <- Lst(l=l) | |
env <- Env(e=list2env(l)) | |
##> system.time(lst@l[["a"]][1,1] <- 1) | |
## user system elapsed | |
## 0.080 0.000 0.077 | |
##> system.time(env@e[["a"]][1,1] <- 1) | |
## user system elapsed | |
## 0.000 0.000 0.005 | |
## Because lst@l is copying the entire object | |
## which also implies memory overhead |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment