Created
January 7, 2026 01:19
-
-
Save J-Moravec/07bde03068ece71495976b0388c4b519 to your computer and use it in GitHub Desktop.
Stack benchmarking
This file contains hidden or 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
| 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