Skip to content

Instantly share code, notes, and snippets.

@hadley
Last active November 10, 2022 20:11
Show Gist options
  • Save hadley/48c396ae674cdccb618033df1b1ed671 to your computer and use it in GitHub Desktop.
Save hadley/48c396ae674cdccb618033df1b1ed671 to your computer and use it in GitHub Desktop.
f1 <- function(n) {
x <- numeric()
for (i in 1:n) {
x <- c(x, i)
}
x
}
f1.5 <- function(n) {
x <- numeric()
for (i in 1:n) {
x[[i]] <- i
}
x
}
f2 <- function(n) {
x <- numeric(n)
for (i in 1:n) {
x[[i]] <- i
}
x
}
bench::mark(f1(1e4), f1.5(1e4), f2(1e4))
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 3 × 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 f1(10000) 109ms 113.34ms 8.77 382MB 77.2
#> 2 f1.5(10000) 936µs 1.05ms 726. 1.68MB 67.6
#> 3 f2(10000) 212µs 216.77µs 4495. 96.77KB 6.00
@hadley
Copy link
Author

hadley commented Nov 10, 2022

I switched both to [[; as I'd expect, that made very little difference.

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