I recently answered a question pertaining to for
loops. Upon testing my code's speed, I noticed that the use of seq()
as opposed to :
in the for
loop slowed the speed down considerably.
Have a look at this very simple example. The only difference between f1()
and f2()
is a change in the for
loop sequence, yet f1()
is over twice as fast as 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
Why is seq(x)
so much slower in a for
loop than 1:length(x)
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…