This example explores the JIT (just-in-time) compilation in R using the compiler package.

Brute-force for loop for summing a vector

testfor <- function(x) {
  sumx <- 0.0
  for (i in 1:length(x)) {
    sumx <- sumx + x[i]
  }
  return(sumx)
}

Vectorized form

testvec <- function(x) {
  return(sum(x))
}

Run the code on 1e6 elements

x = seq(from = 0, to = 100, by = 0.0001)
system.time(testfor(x))
##    user  system elapsed 
##   0.414   0.002   0.415
system.time(testvec(x))
##    user  system elapsed 
##   0.001   0.000   0.001

Let’s load the compiler package and compile the testfor function

library(compiler)
ctestfor <- cmpfun(testfor)

Re-run the functions

system.time(testfor(x))
##    user  system elapsed 
##   0.380   0.002   0.382
system.time(ctestfor(x))
##    user  system elapsed 
##   0.090   0.000   0.091
system.time(testvec(x))
##    user  system elapsed 
##   0.001   0.000   0.001