为什么"colMeans()"和"rowMeans()"的功能要比在"lapply()"中使用均值功能更快? [英] Why are `colMeans()` and `rowMeans()` functions faster than using the mean function with `lapply()`?
问题描述
我想问的是,rowMeans()
和colMeans()
函数在算法上如何优化速度?
What I want to ask is, algorithmically, what do the rowMeans()
and colMeans()
functions do to optimize speed?
推荐答案
此外,请考虑lapply()
的作用.它设置对函数mean()
的重复调用.因此,除了实际计算均值的开销(在快速C代码中完成)之外,lapply()
版本还会反复产生健全性检查代码和与mean()
相关联的方法分派的开销.
In addition, consider what lapply()
does. It sets up repeated calls to the function mean()
. So as well as the overhead of actually computing a mean (which is done in fast C code), the lapply()
version repeatedly incurs the overhead of the sanity checking code and method dispatch associated with mean()
.
rowMeans()
和colMeans()
仅在内部进行一组健全性检查,它们的C代码经过优化,可以循环遍历那里的行/列,而无需通过单独的R调用.
rowMeans()
and colMeans()
incur only a single set of sanity checks as internally, their C code is optimised to loop over the rows/columns there rather than via separate R calls.
这篇关于为什么"colMeans()"和"rowMeans()"的功能要比在"lapply()"中使用均值功能更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!