01 / 20

Vectorization
Performance in R

Understand why vectorized operations dramatically outperform loops in R, and learn to write faster, cleaner code by thinking in vectors.

R Programming

What Is Vectorization?

A vectorized operation applies a function to an entire vector (array of values) in a single call, rather than looping through each element one at a time. In R, most built-in functions and operators are vectorized by default.

Loop vs. Vector: A Visual

Loop Approach x[1] +10 y[1] x[2] +10 y[2] x[3] +10 y[3] ... one at a time Vectorized x[1] x[2] x[3] ... + 10 y[1] y[2] y[3] ... All at once in C/Fortran Slow: many R calls Fast: one C call

Why Does Speed Matter?

R is an interpreted language: each line of R code is translated to machine instructions at runtime. Every iteration of a for loop requires R's interpreter to process the loop logic, check types, and allocate memory individually. When your data grows to millions of rows, this overhead becomes enormous.

10,000 rows
Loops feel OK but vectorization is still \( \sim 10\times \) faster
1 million rows
Loop takes seconds; vectorized takes milliseconds
100 million rows
Loop may take minutes; vectorized finishes in seconds

The Core Principle

The performance gain comes from eliminating three types of per-element overhead:

1
Interpreter overhead: R must parse, evaluate, and dispatch each loop iteration separately
2
Type checking: R checks and coerces data types on every single operation inside a loop
3
Memory allocation: Growing a result vector inside a loop forces repeated memory copies

Under the Hood: Execution Flow

for loop path R Code Interpreter repeat Type Check Alloc Memory C (1 elem)
\( n \) times
Vectorized path R Code Dispatch Compiled C/Fortran
Processes all \( n \) elements
Result vector

Loop vs. Vectorized Code

Loop version
# Slow: element-by-element in R result <- numeric(length(x)) for (i in seq_along(x)) { result[i] <- x[i] * 2 + 1 }
Vectorized version
# Fast: entire vector at once in C result <- x * 2 + 1

The apply Family

R provides the apply family of functions (sapply, lapply, vapply, mapply) as alternatives to explicit loops. However, they are not always truly vectorized: they still loop in R internally but offer cleaner syntax.

Truly Vectorized
Built-in operators: +, *, ^, log(), sqrt(), ifelse(), cumsum()
apply Family
Cleaner than for loops but often no speed gain: loop is just hidden inside the function

Memory: Growing vs. Pre-allocated

Growing (worst case) 1 copy 1 2 copy 1 2 3 copy 1 2 3 4
Total copies: \( O(n^2) \)
Vectorized (pre-allocated) _ _ _ _ Allocate once fill in C 1 2 3 4
Total copies: \( O(n) \)

How to Vectorize Your Code

1
Identify the loop: Find any for or while loop operating on vector elements
2
Check for a built-in: Does R have a vectorized function for this? (e.g., sum(), cumsum(), ifelse(), pmin(), paste0())
3
Replace the loop: Rewrite the operation as a single vectorized expression
4
Benchmark: Use system.time() or the microbenchmark package to confirm the speedup
5
If no built-in exists: Consider Rcpp to write a C++ loop, or at minimum pre-allocate your result vector

Example 1: Squaring a Vector

Task: compute \( y_i = x_i^2 \) for every element of a vector x with \( n = 1{,}000{,}000 \) elements.

Loop
y <- numeric(n) for (i in 1:n) { y[i] <- x[i]^2 }
Vectorized
y <- x^2

Example 2: Conditional Replacement

Task: replace all negative values in a vector with \( 0 \).

Loop
for (i in seq_along(x)) { if (x[i] < 0) x[i] <- 0 }
Vectorized (two approaches)
# Using logical indexing x[x < 0] <- 0 # Using ifelse() x <- ifelse(x < 0, 0, x) # Using pmax() x <- pmax(x, 0)

Example 3: Row Sums of a Matrix

Task: compute the sum of each row in a \( 10{,}000 \times 100 \) matrix.

Loop
sums <- numeric(nrow(mat)) for (i in 1:nrow(mat)) { sums[i] <- sum(mat[i, ]) }
apply (hidden loop)
sums <- apply(mat, 1, sum)
Truly vectorized
sums <- rowSums(mat)

Benchmark Comparison

Time (ms) 200 150 100 50 0 197 Growing loop 85 Pre-alloc loop 68 sapply 3 Vectorized

Common Mistakes

✕ Growing vectors
Using c(result, x) inside a loop copies the entire vector every iteration: \( O(n^2) \) cost
✕ Thinking apply = vectorized
The apply family hides loops but doesn't eliminate interpreter overhead. Only built-in C-level functions are truly vectorized.
✕ Unnecessary loops for math
Writing a loop for x * 2 + 1 when R's arithmetic operators already handle entire vectors natively

Summary Comparison

for Loop apply Family Vectorized
Loop runs in R interpreter R interpreter Compiled C/Fortran
Type checking Every iteration Every iteration Once at dispatch
Memory allocation Risk of growing Pre-allocated internally Optimal batch alloc
Code readability Verbose Moderate Concise
Relative speed \( 1\times \) \( 1\text{-}2\times \) \( 10\text{-}100\times \)

Question 1 of 5

Why is x^2 faster than a for loop that squares each element individually?

Question 2 of 5

Which of the following is a truly vectorized function (not just a hidden loop)?

Question 3 of 5

What is the primary problem with growing a vector inside a loop using c(result, new_value)?

Question 4 of 5

You want to replace all values greater than 100 with 100 in a vector x. Which is the best vectorized approach?

Question 5 of 5

Which of the following lists the three main sources of overhead that vectorization eliminates?