我的S4类有一个多次调用的方法。我注意到执行时间比单独调用类似函数时慢得多。所以我在类中添加了一个类型为“function”的插槽,并使用该函数代替方法。下面的例子显示了这样做的两种方式,并且它们都比对应的方法运行速度快得多。另外,该例子表明,该方法的速度较低并不是由于方法必须从类中检索数据,因为即使他们也这样做,函数的速度更快。S4方法调度缓慢吗?
当然,这种做事方式并不理想。我想知道是否有办法加快方法调度。有什么建议么?
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([email protected]))
}
)
setGeneric(
name = "create.foo2",
def = function(object) {standardGeneric("create.foo2")}
)
setMethod(
f = "create.foo2",
signature = "SpeedTest",
definition = function(object) {
z <- [email protected]
[email protected] <- function() sqrt(abs(z))
object
}
)
> st <- speedTest(1000)
> st <- create.foo2(st)
>
> iters <- 100000
>
> system.time(for (i in seq(iters)) method.foo(st)) # slowest by far
user system elapsed
3.26 0.00 3.27
> # much faster
> system.time({foo1 <- [email protected]; x <- [email protected]; for (i in seq(iters)) foo1(x)})
user system elapsed
1.47 0.00 1.46
> # retrieving [email protected] instead of x does not affect speed
> system.time({foo1 <- [email protected]; for (i in seq(iters)) foo1([email protected])})
user system elapsed
1.47 0.00 1.49
> # same speed as foo1 although no explicit argument
> system.time({foo2 <- [email protected]; for (i in seq(iters)) foo2()})
user system elapsed
1.44 0.00 1.45
# Cannot increase speed by using a lambda to "eliminate" the argument of method.foo
> system.time({foo <- function() method.foo(st); for (i in seq(iters)) foo()})
user system elapsed
3.28 0.00 3.29
感谢您的有用建议。我的数据表示和方法没有被矢量化的原因是:我正在使用多态。在我的代码中,每个子类都有不同的method.foo,不同的人可能会编写不同的方法。因此,与示例不同,每次调用method.foo都调用不同的方法,我不知道每个方法的内容是什么。 – Soldalma 2013-05-06 15:06:20