adaien
adaien

Reputation: 1942

Are while loops as slow as the for loops in R?

For loops are know to be quite slow in R. I would like to know if the same is true for while loop.

If so, is there a way to optimize while loop in R? For example for the for loop the apply functions play a good job but I don't know an analogue for the while loop.

Even Hadley in his book (Advanced R) is quite vague about how to optimize a while loop.

Upvotes: 1

Views: 4092

Answers (1)

Roland
Roland

Reputation: 132874

"For loops are know to be quite slow in R." That's simply wrong. for loops are fast. What you do inside the loop is slow (in comparison to vectorized operations). I would expect a while loop to be slower than a for loop since it needs to test a condition before each iteration. Keep in mind that R is an interpreted language, i.e., there are no compiler optimizations. Also, function calls in R are not slow per se, but still there is a lot going on during a function call and that adds up. Vectorized operations avoid repeated function calls.

It's hard to come up with a fair comparison between both loop construct, but here we go:

library(microbenchmark)

microbenchmark(
  for (i in seq_len(1e6)) i,
  {i <- 1; while (i <= 1e6) {i <- i+1}},
  times = 10, unit = "relative"
)

#Unit: relative
#                                                             expr      min       lq    mean   median       uq      max neval cld
#                                      for (i in seq_len(1e+06)) i 1.000000 1.000000 1.00000 1.000000 1.000000  1.00000    10  a 
# {     i <- 1     while (i <= 1e+06) {         i <- i + 1     } } 8.987293 8.994548 9.14089 9.019795 9.036116 10.07227    10   b

The while loop needs to test the condition, assign to i and call + at each iteration.

If you must use a while loop (often it can be avoided) and performance is important, the best solution is implementing it as compiled code which can be called from R. The Rcpp package makes this very easy. In some cases byte compilation as offered by the compiler package can also speed up R loops, but (well written) actual compiled code will always be faster.

Upvotes: 5

Related Questions