问题
> system.time(sapply(rnorm(1000000,0,1), function (x) round(x,2)))
user system elapsed
2.78 0.11 2.89
> system.time(round(rnorm(1000000,0,1),2))
user system elapsed
0.29 0.00 0.30
I was trying this out after reading the answers to the R tips question. I did not expect sapply to be order of magnitude slower than the equivalent composite function in the above case. Does anyone know why this is the case? If i understand correctly sapply will vectorize and be near optimally fast.
回答1:
There's nothing here to sapply to - you only give it a single vector - not a list of vectors, and sapply converts the result to a (single column) matrix.
sapply is simplifying the result for you, but in doing so has to generate an array.
Compare if you give it a list:
system.time(sapply(list(rnorm(1000000,0,1)), function (x) round(x,2)))
user system elapsed
0.22 0.00 0.22
system.time(sapply(rnorm(1000000,0,1), function (x) round(x,2)))
user system elapsed
4.21 0.00 4.21
回答2:
probably sapply, which is a simple wrapper of lapply, is not vectorized. try this code:
system.time(sapply(rnorm(10), function (x) {print(length(x)); round(x,2)}))
and see the implementation here: https://svn.r-project.org/R/trunk/src/main/apply.c
来源:https://stackoverflow.com/questions/4600243/speed-comparison-of-sapply-with-a-composite-function