Looking at speed

by Karl-Kuno Kunze

This post wants to remind you of the package compiler by Luke Tierney and to somehow save the honor of the for loop that is rather likely to be discredited by R users.

As an ardent admirer of all functions with a ply inside I cannot help but praise the elegance of avoiding everything with a for inside. However, every now and then fervent disregard of the for loop may lead to more elegant but slower code. In the following we write some purely demonstrative code and take a look at time consumption.


There is nothing slower than a for loop. Let us write some code that is slow on purpose:

SQvecFL <- function(x) {
  sq <- numeric(length(x))
  for (i in 1:length(x))
    sq[i] <- x[i]^2 
##    user  system elapsed 
##   1.650   0.021   1.671

We take every single element of the vector, square it and then return it. That must be slow.

Now, we rewrite the function with a somewhat accelerated version of the apply function: vapply().

SQvecvA <- function(x) {
  vapply(x, function(x) x^2, FUN.VALUE = c(1))
##    user  system elapsed 
##   0.707   0.005   0.711

As expected, this one is more elegant and faster.


Using the compiler package, this can be speeded up by some amount. Let us first speed up the loop:

SQvecCompFL <- cmpfun(SQvecFL)
##    user  system elapsed 
##   0.487   0.010   0.499

That is about a third the previous running time.

Let us redo the same with the vapply() function:

SQvecvAComp <- cmpfun(SQvecvA)
##    user  system elapsed 
##   0.631   0.001   0.632

That is a lean 10% more efficiency. And it is slower than the for loop!


Never would anybody solve a problem like this with code like that. This line

##    user  system elapsed 
##   0.004   0.000   0.005

gives breathtaking proof of the vector-valued paradigm.

However, keep compiling in mind. Not always does it speed-up your code but it should be worth a try. And why not write a for loop every now and then…

Title photo: Maik Schwertle/ pixelio.de