Introduction

Quite often I write which(...)[1] to find the first element of a vector matching some condition. One has to wonder whether that’s wasteful, though, since there is no need to do any tests once one works. I decided to try using C++, using Rcpp, to see if speed advances could be made.

Procedure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
library(Rcpp)
library(microbenchmark)
cppFunction('
int firstZero(IntegerVector x) {
int nx = x.size();
for (int i = 0; i < nx; ++i) {
if (0 == x[i]) {
return i+1;
}
}
return 0; // means none found
}'

)
x <- rep(1, 10000)
x[seq.int(500, 10000)] <- 0
microbenchmark(firstZero(x), times=1000L)
## Unit: microseconds
## expr min lq median uq max neval
## firstZero(x) 23.46 23.75 23.87 24.14 1065 1000
1
microbenchmark(which(0==x)[1], times=1000L)
## Unit: microseconds
## expr min lq median uq max neval
## which(0 == x)[1] 52.4 53.59 54.14 54.84 1124 1000

Results

The C++ method was nearly twice as fast. However, other tests (with different vector lengths, different fractions zeroed-out, etc) showed nearly identical times for the two methods.

Conclusions

In light of variations in test results, and the added complexity of including C++ code in an R program, I advise carrying out data-tailored benchmarks before deciding to use Rcpp.

Note that the test does not account for the time to compile the C++ program, which can outweigh time savings in small problems. However, this is irrelevant because one shouldn’t be worrying about optimization in small problems anyway, and large problems will likely involve package generation, which means that the C++ compilation will be done as the package is being built.

Resources

This website is written in Jekyll, and the source is available on GitHub.