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:

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().

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:

That is about a third the previous running time.

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

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

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