Vectorization
Performance in R
Understand why vectorized operations dramatically outperform loops in R, and learn to write faster, cleaner code by thinking in vectors.
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
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.
The Core Principle
The performance gain comes from eliminating three types of per-element overhead:
Under the Hood: Execution Flow
Loop vs. Vectorized Code
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.
Memory: Growing vs. Pre-allocated
How to Vectorize Your Code
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.
Example 2: Conditional Replacement
Task: replace all negative values in a vector with \( 0 \).
Example 3: Row Sums of a Matrix
Task: compute the sum of each row in a \( 10{,}000 \times 100 \) matrix.
Benchmark Comparison
Common Mistakes
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?