Skip to content

Instantly share code, notes, and snippets.

@J-Moravec
Created January 7, 2026 01:19
Show Gist options
  • Select an option

  • Save J-Moravec/07bde03068ece71495976b0388c4b519 to your computer and use it in GitHub Desktop.

Select an option

Save J-Moravec/07bde03068ece71495976b0388c4b519 to your computer and use it in GitHub Desktop.
Stack benchmarking
new_stack = function(capacity){
size = 0
items = vector("numeric", capacity)
add = function(x){
size <<- size + 1
items[size] <<- x
}
get = function(){
items[seq_len(size)]
}
environment()
}
new_stack2 = function(n){
items = numeric()
add = function(x){
items <<- c(items, x)
}
get = function(){
items
}
environment()
}
test = function(stack, n = 1000, every = 1){
for(i in seq_len(n)){
stack$add(i)
if(!i %% every)
stack$get()
}
}
# for small n and small every, there is no value in pre-allocating
# for n~100 and every~4, there is very little difference
# for n~1000 and every~100, the pre-allocated stack is ~2x faster and 40x more memory efficient
n = 1000
every = 100
bench::mark(
test(new_stack(n), n, every),
test(new_stack2(), n, every)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment