24.2 Organizing code

  • Write a function for each approach
mean1 <- function(x) mean(x)
mean2 <- function(x) sum(x) / length(x)
  • Keep old functions that you’ve tried, even the failures
  • Generate a representative test case
x <- runif(1e5)
  • Use bench::mark to compare the different versions (and include unit tests)
bench::mark(
  mean1(x),
  mean2(x)
)[c("expression", "min", "median", "itr/sec", "n_gc")]
#> # A tibble: 2 × 4
#>   expression      min   median `itr/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl>
#> 1 mean1(x)      379µs    440µs     2262.
#> 2 mean2(x)      186µs    187µs     5277.