我的S4类有一个多次调用的方法.我注意到执行时间比独立调用类似函数时要慢得多.所以我在我的类中添加了一个带有"function"类型的插槽,并使用该函数而不是方法.下面的示例显示了两种执行此操作的方法,它们都比相应的方法运行得快得多.此外,该示例表明该方法的较低速度不是由于必须从类中检索数据的方法,因为即使它们也这样做,功能也更快.
当然,这种做事方式并不理想.我想知道是否有办法加速方法调度.有什么建议?
setClass(Class = "SpeedTest",
representation = representation(
x = "numeric",
foo1 = "function",
foo2 = "function"
)
)
speedTest <- function(n) {
new("SpeedTest",
x = rnorm(n),
foo1 = function(z) sqrt(abs(z)),
foo2 = function() {}
)
}
setGeneric(
name = "method.foo",
def = function(object) {standardGeneric("method.foo")}
)
setMethod(
f = "method.foo",
signature = "SpeedTest",
definition = function(object) {
sqrt(abs(object@x))
}
)
setGeneric(
name = "create.foo2",
def = function(object) {standardGeneric("create.foo2")}
)
setMethod(
f = "create.foo2",
signature = "SpeedTest",
definition = function(object) { …
Run Code Online (Sandbox Code Playgroud)