Created
July 29, 2012 12:04
-
-
Save musically-ut/3198222 to your computer and use it in GitHub Desktop.
Four different ways of creating lists
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
f1 <- function (n) { | |
l <- list() | |
for(idx in 1:n) { | |
l <- append(l, idx) | |
} | |
return(l) | |
} | |
f2 <- function (n) { | |
l <- list() | |
for(idx in 1:n) { | |
l[[length(l) + 1]] <- idx | |
} | |
return(l) | |
} | |
f3 <- function (n) { | |
l <- vector("list", n) | |
for(idx in 1:n) { | |
l[[idx]] <- idx | |
} | |
return(l) | |
} | |
f4 <- function (n) { | |
return(as.list(sapply(1:n, function (idx) idx))) | |
} | |
warm.up <- function(f, n, times) { | |
system.time(sapply(1:times, function (i) f(n)), gcFirst=T) | |
} | |
run.all <- function (reps=10) { | |
timesSeq <- seq(from=10, to=10000, by=100) | |
message("Running f1 ...") | |
f1.prof <- sapply(timesSeq[1:50], function (arg) warm.up(f1, arg, reps)[1] / reps) | |
message("Running f2 ...") | |
f2.prof <- sapply(timesSeq, function (arg) warm.up(f2, arg, reps)[1] / reps) | |
message("Running f3 ...") | |
f3.prof <- sapply(timesSeq, function (arg) warm.up(f3, arg, reps)[1] / reps) | |
message("Running f4 ...") | |
f4.prof <- sapply(timesSeq, function (arg) warm.up(f4, arg, reps)[1] / reps) | |
return(list( | |
timesSeq=timesSeq, | |
f1.prof=f1.prof, | |
f2.prof=f2.prof, | |
f3.prof=f3.prof, | |
f4.prof=f4.prof | |
)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment