0Pricing
R Academy · Lesson

Vectorization for Speed

Replace explicit loops with vectorized operations for major speedups.

Why Vectorization Matters

R is an interpreted language, so for loops have overhead on every iteration — function call dispatch, bounds checking, type coercion. Vectorized operations push that work into compiled C code that runs orders of magnitude faster.

Vectorization is the single most impactful optimization available in base R.

Loop vs cumsum() Example

Computing a running total with a for loop versus the built-in cumsum() shows the gap clearly. cumsum() calls C-level compiled code and processes the entire vector in one pass.

n <- 500000
x <- rnorm(n)

t_loop <- system.time({
  result <- numeric(n)
  result[1] <- x[1]
  for (i in 2:n) result[i] <- result[i-1] + x[i]
})['elapsed']

t_vec <- system.time({
  result2 <- cumsum(x)
})['elapsed']

cat('Loop  :', t_loop, 's
')
cat('cumsum:', t_vec, 's
')

All lessons in this course

  1. system.time() and proc.time()
  2. Profiling Code with Rprof and profvis
  3. Vectorization for Speed
  4. Benchmarking with microbenchmark
← Back to R Academy