Add a Cpp function to existing R6 Class

in src/testMethods.cpp we define a function to use RcppArmadillo to do matrix multiplication on hte two matrices initialized in testClass. R/testClasses.R defines the R6 object as well as a function addRcppMethod that adds the cpp method testMethodCpp to the R6ClassGenerator object.

Note that addRcppMethod actually defines the new method testClass$testMethodCpp() as a wrapper that passes the private environment down to the actual C++ code. This is because I have not been able to figure out so far how to directly “look up” to the enclosing R6 object from C++ and pull out the private enrivonment. Therefore we must use a wrapper to pass down that environment.

Future testing:

  • Can we directly grab the public environment from within the C++ code?
  • We should also test to make sure the environment is being passed as a reference and not being copied (maybe we can force this with const Rcpp::Environment &testClassEnv, also research into this option.)

The ultimate irony is that C++ is slower than R here. Always optimize intelligently! Compiled code is not always faster code.

library(microbenchmark)
library(RcppQueues)
## 
## Attaching package: 'RcppQueues'
## The following object is masked from 'package:utils':
## 
##     stack
addRcppMethod()
xx = testClass$new(500)
microbenchmark(xx$testMethod(),xx$testMethodCpp())
## Unit: milliseconds
##                expr      min       lq     mean   median       uq      max
##     xx$testMethod() 1.788029 2.118452 2.720598 2.405273 2.690040 31.70748
##  xx$testMethodCpp() 2.195743 2.480290 3.191838 2.783275 3.112033 34.27963
##  neval
##    100
##    100