Skip to content

Instantly share code, notes, and snippets.

@jrosell
Created August 30, 2023 07:56
Show Gist options
  • Save jrosell/ebb604e8c35a8665e2380ef3ea952464 to your computer and use it in GitHub Desktop.
Save jrosell/ebb604e8c35a8665e2380ef3ea952464 to your computer and use it in GitHub Desktop.
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))
@jrosell
Copy link
Author

jrosell commented Aug 30, 2023

# A tibble: 4 × 5
  expression             median `itr/sec` mem_alloc times_faster
                           
1 vector_c              581.3µs     1111.    1.97MB         1   
2 vector_c_unlist       236.9µs     3783.   56.79KB         2.45
3 unalloc_two_bracket   230.9µs     3750.  190.35KB         2.52
4 prealloc_two_bracket   26.8µs    35908.   26.84KB        21.7 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment