Class activity solutions

Author

Ciaran Evans

  1. Using crossprod is substantially faster
x <- rnorm(100)
w <- runif(100)

bench::mark(
  weighted_means <- sum(x*w),
  weighted_means <- crossprod(x, w),
  check = F
)
# A tibble: 2 × 6
  expression                            min  median `itr/sec` mem_alloc `gc/sec`
  <bch:expr>                        <bch:t> <bch:t>     <dbl> <bch:byt>    <dbl>
1 weighted_means <- sum(x * w)      12.29µs 12.54µs    77559.      848B      0  
2 weighted_means <- crossprod(x, w)  1.25µs  1.38µs   700247.    2.23KB     70.0
  1. The relative speed stays about the same.
x <- rnorm(100000)
w <- runif(100000)

bench::mark(
  weighted_means <- sum(x*w),
  weighted_means <- crossprod(x, w),
  check = F
)
# A tibble: 2 × 6
  expression                            min  median `itr/sec` mem_alloc `gc/sec`
  <bch:expr>                        <bch:t> <bch:t>     <dbl> <bch:byt>    <dbl>
1 weighted_means <- sum(x * w)       11.5ms  11.6ms      86.3     781KB        0
2 weighted_means <- crossprod(x, w) 166.6µs 167.1µs    5908.         0B        0
random_string <- function() {
  paste(sample(letters, 50, replace = TRUE), collapse = "")
}
strings <- replicate(10, random_string())

collapse <- function(xs) {
  out <- ""
  for (x in xs) {
    out <- paste0(out, x)
  }
  out
}

bench::mark(
  collapse(strings),
  paste(strings, collapse="")
)
# A tibble: 2 × 6
  expression                            min  median `itr/sec` mem_alloc `gc/sec`
  <bch:expr>                        <bch:t> <bch:t>     <dbl> <bch:byt>    <dbl>
1 "collapse(strings)"               20.88µs 21.96µs    45131.      16KB     18.1
2 "paste(strings, collapse = \"\")"  4.42µs  4.67µs   209927.        0B      0