# 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)

1

microbenchmark(which(0==x)[1], times=1000L)

# 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

- Source code: 2014-06-08-Rcpp.R