Skip to content

Instantly share code, notes, and snippets.

@musically-ut
Created July 29, 2012 12:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save musically-ut/3198222 to your computer and use it in GitHub Desktop.
Save musically-ut/3198222 to your computer and use it in GitHub Desktop.
Four different ways of creating lists
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