Performance
Pitfalls in R
Learn why growing vectors in loops silently destroys your code's speed, and discover idiomatic R patterns that run orders of magnitude faster.
What Is a Performance Pitfall?
A performance pitfall is a coding pattern that looks correct and produces the right answer, but runs dramatically slower than necessary. In R, the most notorious pitfall is growing a vector inside a loop: appending one element at a time instead of pre-allocating memory.
Why R Memory Works Differently
R vectors live in contiguous blocks of memory. When you append an element, R cannot just tack it on the end. Instead, it must:
The Hidden Cost Visualized
The Golden Rule of R Loops
Copy-on-Append Under the Hood
Append vs. Index Assignment
c(result, x)result[i] <- xHow to Fix a Growing-Vector Loop
numeric(n), character(n), logical(n), or vector("list", n).result[i] <- value instead of result <- c(result, value).sapply(), vapply(), purrr::map(), or direct vectorized operations can eliminate the loop entirely.Example 1: Computing Squares
Example 2: Filtering Even Numbers
Example 3: Building a Character Vector
paste0() in a looppaste0()Beyond Loops: The apply Family
When you must apply a function element-by-element but want to avoid manual pre-allocation, R's apply family handles memory for you:
Real Benchmark Numbers
Common Mistakes
c() to appendresult <- c(result, x) inside a loop triggers a full copy every iteration, producing \(O(n^2)\) behaviour.append()append() function is equally slow: it still creates a new vector and copies everything.numeric(n) when you need characters causes coercion inside the loop, adding hidden overhead.Strategy Comparison
| Strategy | Time Complexity | Memory Copies | Recommended? |
|---|---|---|---|
c() append in loop |
\( O(n^2) \) | \( \frac{n(n-1)}{2} \) | Never |
| Pre-alloc + index | \( O(n) \) | 0 | Yes |
| sapply / vapply | \( O(n) \) | 0 | Yes |
| Vectorized operation | \( O(n) \) | 0 | Best |
Question 1 of 5
What happens in memory when you execute result <- c(result, new_value) inside a loop?
c() forces a full reallocation and copy of every existing element.Question 2 of 5
If you grow a vector one element at a time in a loop of \(n\) iterations, how many total element copies are performed?
Question 3 of 5
Consider the following R code:
Which statement about this code is true?
numeric(length(x)) and fills by index. The loop itself is \(O(n)\). Loops are not inherently slow: growing vectors inside them is.Question 4 of 5
Which of the following is the best replacement for a loop that squares every element of a numeric vector x?
Question 5 of 5
A student claims: "R loops are always slow, so you should never use a for loop." Is this statement correct?