Why is seq(x) so much slower than 1:length(x)?

后端 未结 3 1541
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 07:25

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 :

3条回答
  •  臣服心动
    2020-12-14 08:18

    Using seq_len you get nearly the same time as the : operator:

    f3 <- function(){
      x <- 1:5; y <- numeric(length(x))
      for(i in seq_len(length(x))) y[i] <- x[i]^2
      y
    }
    
    library(microbenchmark)
    microbenchmark(f1(), f2(),f3())
    
    Unit: microseconds
     expr    min      lq  median     uq    max neval
     f1()  9.988 10.6855 10.9650 11.245 50.704   100
     f2() 23.257 23.7465 24.0605 24.445 88.140   100
     f3() 10.127 10.5460 10.7555 11.175 18.857   100
    

    Internally seq is doing many verifications before calling : or seq_len.

提交回复
热议问题