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

后端 未结 3 1543
佛祖请我去吃肉
佛祖请我去吃肉 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:24

    seq is a generic S3 method, so probably some time is lost dispatching. seq.default is almost 100 lines long!

    You're probably already aware of seq_along, which calls a .Primitive directly and is bit better than 1:length(x) and the best method I have found for long loops:

    f3 <- function(){
          x <- 1:5; y <- numeric(length(x))
          for(i in seq_along(x)) y[i] <- x[i]^2
          y
      }
    >  microbenchmark(f1(), f3())
    Unit: microseconds
     expr    min     lq median     uq    max neval
     f1() 27.095 27.916 28.327 29.148 89.495   100
     f3() 26.684 27.505 27.916 28.327 36.538   100
    

提交回复
热议问题