General principle: Memory allocation

Writing Efficient R Code

Colin Gillespie

Jumping Rivers & Newcastle University

Writing Efficient R Code

If we programmed in C...

We're in charge of memory allocation
// C code: request memory for a number
x = (double *) malloc(sizeof(double));

// Free the memory
free(x);
  • In R, memory allocation happens automatically
  • R allocates memory in RAM to store variables
  • Minimize variable assignment for speed
Writing Efficient R Code

Example: Sequence of integers

$$ 1, 2, \ldots, n $$

The obvious and best way
## Method 1
x <- 1:n
Not so bad
## Method 2
x <- vector("numeric", n) # length n
for(i in 1:n)
    x[i] <- i
Don't ever do this!
## Method 3
x <- NULL # Length zero
for(i in 1:n)
    x <- c(x, i)
Writing Efficient R Code

Benchmarking

  • Method 1: 1:n
  • Method 2: Preallocate
  • Method 3: Growing
Time in seconds
n 1 2 3
$10^5$ 0.00 0.02 0.2
$10^6$ 0.00 0.2 30
$10^7$ 0.00 2 3800

Writing Efficient R Code

Welcome to R club!

The first rule of R club: never, ever grow a vector.

Writing Efficient R Code

Let's practice!

Writing Efficient R Code

Preparing Video For Download...