我最近回答了有關for
循環的問題。在測試我的代碼的速度時,我注意到在for
循環中使用seq()
而不是:
會顯着減慢速度。爲什麼seq(x)比1:length(x)慢得多?
看看這個非常簡單的例子。 f1()
和f2()
之間的唯一區別在於for
循環序列的變化,但f1()
的速度是f2()
的兩倍。
f1 <- function() {
x <- 1:5; y <- numeric(length(x))
for(i in 1:length(x)) y[i] <- x[i]^2
y
}
f2 <- function() {
x <- 1:5; y <- numeric(length(x))
for(i in seq(x)) y[i] <- x[i]^2
y
}
library(microbenchmark)
microbenchmark(f1(), f2())
# Unit: microseconds
# expr min lq median uq max neval
# f1() 10.529 11.5415 12.1465 12.617 33.893 100
# f2() 25.052 25.5905 26.0385 28.759 78.553 100
爲什麼比1:length(x)
一個for
循環是seq(x)
這麼多慢?