I have been writing code using R reference classes. However, as I have progressed, the program has become intolerably slow. To demonstrate the problem, take the following example:
myClass <- setRefClass(
"Class"="myClass",
fields=c(
counter="numeric"
),
methods=list(
initialize=function () {
counter <<- 0
},
donothing=function () {
},
rand=function () {
return(runif(1))
},
increment=function () {
counter <<- counter + 1
}
)
)
mc <- myClass()
system.time(for (it in 1:500000) {
mc$donothing()
})
system.time(for (it in 1:500000) {
mc$rand()
})
system.time(for (it in 1:500000) {
mc$increment()
})
It takes:
- 4s for calls to a method
- 7s for calls to generate a random number
- 19s to increment a field value
It's the last result that's causing me problems. I obviously don't expect it to take twice as long to increment a number than to generate a random number. My code involves a lot of accessing and changing of field values in a reference class, and this performance issue has made the program all but usable.
My question: is there anything I can do to improve the performance of field lookup/access in R reference classes? Is there anything I should be doing differently?