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

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

    A more specific reason why it's slower:

    seq(x) will call seq.default*, and seq.default calls 1L:x!!

    From seq.default:

    if ((One <- nargs() == 1L) && !missing(from)) {
        lf <- length(from)
        return(if (mode(from) == "numeric" && lf == 1L) {
            #checks validity -- more slow-down
            if (!is.finite(from)) stop("'from' cannot be NA, NaN or infinite")
            #boom! under the hood, seq.default is doing 1:N
            1L:from
        #looks like it defaults to seq_along if length(from) > 1?
        } else if (lf) 1L:lf else integer())
    }
    

    *Unless, of course, x is Date or POSIXt, or you have another library loaded that has a seq method...

提交回复
热议问题