Starting with version 2.13, R has included a byte code compiler, which you can use to try to speed up your code. Consider our example from Section 14.2.1. As a trivial example, we showed that
z <- x + y
was much faster than
for (i in 1:length(x)) z[i] <- x[i] + y[i]
Again, that was obvious, but just to get an idea of how byte code compilation works, let’s give it a try:
> library(compiler) > f <- function() for (i in 1:length(x)) z[i] <<- x[i] + y[i] > cf <- cmpfun(f) > system.time(cf()) user system elapsed 0.845 0.003 0.848
We created a new function, cf()
, from the original f()
. The new code’s run time was 0.848 seconds, much faster than the 8.175 seconds the noncompiled version took. Granted, it still wasn’t as fast as the straightforward vectorized code, but it is clear that byte code compilation has potential. You should try it whenever you need faster code.