我一直在使用R 参考类编写代码。然而,随着我的进步,程序变得慢得令人无法忍受。为了演示这个问题,举个例子:
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()
})
它需要:
- 调用方法的 4s
- 7s 调用生成随机数
- 19s 增加一个字段值
这是给我带来问题的最后一个结果。我显然不希望增加一个数字比生成一个随机数花费两倍的时间。我的代码涉及大量访问和更改引用类中的字段值,而这个性能问题使程序几乎可用。
我的问题:我能做些什么来提高 R 参考类中字段查找/访问的性能吗?有什么我应该做的不同的事情吗?