Created
August 30, 2023 07:56
-
-
Save jrosell/ebb604e8c35a8665e2380ef3ea952464 to your computer and use it in GitHub Desktop.
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(tidyverse) | |
n <- 1000 | |
v <- 1:n | |
vector_c <- function(n) { | |
out <- c() | |
for (i in 1:n) { | |
out <- c(out, i) | |
} | |
out | |
} | |
vector_unalloc_two_bracket <- function(n) { | |
out <- c() | |
for (i in 1:n) { | |
out[[i]] <- i | |
} | |
unlist(out) | |
} | |
vector_prealloc_two_bracket <- function(n) { | |
out <- vector("numeric", n) | |
for (i in 1:n) { | |
out[[i]] <- i | |
} | |
out | |
} | |
vector_c_unlist <- function(n) { | |
results <- vector(mode = "list", length = n) | |
results[[1]] <- v[1] | |
for (i in 1:(n-1)){ | |
results[[i]] <- c(results[i], v[i+1]) | |
} | |
results |> unlist() | |
} | |
bench::mark( | |
vector_c = vector_c(n), | |
prealloc_two_bracket = vector_prealloc_two_bracket(n), | |
unalloc_two_bracket = vector_unalloc_two_bracket(n), | |
vector_c_unlist = vector_c_unlist(n), | |
filter_gc = FALSE | |
) %>% | |
select("expression", "median", "itr/sec", "mem_alloc") %>% | |
arrange(desc(median)) %>% | |
mutate(times_faster = as.double(first(median)/median)) |
Author
jrosell
commented
Aug 30, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment