Why are loops slow in R?

It’s not always the case that loops are slow and apply is fast. There’s a nice discussion of this in the May, 2008, issue of R News:

Uwe Ligges and John Fox. R Help Desk: How can I avoid this loop or
make it faster? R News, 8(1):46-50, May 2008.

In the section “Loops!” (starting on pg 48), they say:

Many comments about R state that using loops is a particularly bad idea. This is not necessarily true. In certain cases, it is difficult to write vectorized code, or vectorized code may consume a huge amount of memory.

They further suggest:

  • Initialize new objects to full length before the loop, rather
    than increasing their size within the loop.
  • Do not do things in a
    loop that can be done outside the loop.
  • Do not avoid loops simply
    for the sake of avoiding loops.

They have a simple example where a for loop takes 1.3 sec but apply runs out of memory.

Leave a Comment