01 / 20

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.

R Programming

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:

1
Allocate a brand-new block of memory large enough for the old vector + 1 element.
2
Copy every existing element into the new block.
3
Add the new element at the end, then free the old block.

The Hidden Cost Visualized

Loop Iterations (n) Total Copies 0 200 400 600 800 1000 0 125k 250k 375k 500k
Growing: \( O(n^2) \)
Pre-allocated: 0 copies

The Golden Rule of R Loops

1. Pre-allocate result 2. Loop: fill by index
3. Done: \( O(n) \) total
vs. 1. Start empty 2. Loop: append each
3. Slow: \( O(n^2) \) total

Copy-on-Append Under the Hood

Iter 1 1 1 slot allocated Iter 2 1 → 1 2 copy 1, add 1 Iter 3 → 1 2 3 copy 2, add 1 Iter 4 → 1 2 3 4 copy 3, add 1
Total copies after 4 iterations: \( 0 + 1 + 2 + 3 = 6 \)
General formula for \( n \) iterations: \( \frac{n(n-1)}{2} \)

Append vs. Index Assignment

c(result, x)
Creates a new vector every iteration. Old vector is copied then discarded. Complexity grows as \(O(n^2)\).
result[i] <- x
Writes directly into the existing slot. No copying, no reallocation. Stays at \(O(n)\) total.

How to Fix a Growing-Vector Loop

1
Determine the output length before the loop starts. Usually this equals the input length or some known \(n\).
2
Pre-allocate with the correct type: numeric(n), character(n), logical(n), or vector("list", n).
3
Use index assignment inside the loop: result[i] <- value instead of result <- c(result, value).
4
Consider vectorized alternatives: sapply(), vapply(), purrr::map(), or direct vectorized operations can eliminate the loop entirely.

Example 1: Computing Squares

✕ Slow: Growing Vector
result <- c() for (i in 1:10000) { result <- c(result, i^2) }
✓ Fast: Pre-allocated
result <- numeric(10000) for (i in 1:10000) { result[i] <- i^2 }

Example 2: Filtering Even Numbers

✕ Slow: Growing Vector
evens <- c() for (x in data) { if (x %% 2 == 0) { evens <- c(evens, x) } }
✓ Fast: Vectorized
evens <- data[data %% 2 == 0]

Example 3: Building a Character Vector

✕ Slow: paste0() in a loop
labels <- c() for (i in 1:n) { labels <- c(labels, paste0("item_", i)) }
✓ Fast: Vectorized paste0()
labels <- paste0("item_", 1:n)

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:

sapply()
Applies a function to each element; simplifies to a vector or matrix. Good for quick interactive work.
vapply()
Like sapply(), but you specify the return type. Safer for production code: fails early on unexpected output.
lapply()
Always returns a list. Use when each iteration returns a different type or length.

Real Benchmark Numbers

Approach Time (seconds) 0 2 4 6 8 10 9.2s c() append 0.15s Pre-alloc 0.002s Vectorized

Common Mistakes

✕ Using c() to append
Writing result <- c(result, x) inside a loop triggers a full copy every iteration, producing \(O(n^2)\) behaviour.
✕ Growing with append()
The append() function is equally slow: it still creates a new vector and copies everything.
✕ Wrong pre-alloc type
Using 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?

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

Which statement about this code is true?

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?