Why are loops slow in R?

前端 未结 4 1932
日久生厌
日久生厌 2020-11-22 15:05

I know that loops are slow in R and that I should try to do things in a vectorised manner instead.

But, why? Why are loops slow and apply i

4条回答
  •  伪装坚强ぢ
    2020-11-22 15:45

    Just as a comparison (don't read too much into it!): I ran a (very) simple for loop in R and in JavaScript in Chrome and IE 8. Note that Chrome does compilation to native code, and R with the compiler package compiles to bytecode.

    # In R 2.13.1, this took 500 ms
    f <- function() { sum<-0.5; for(i in 1:1000000) sum<-sum+i; sum }
    system.time( f() )
    
    # And the compiled version took 130 ms
    library(compiler)
    g <- cmpfun(f)
    system.time( g() )
    

    @Gavin Simpson: Btw, it took 1162 ms in S-Plus...

    And the "same" code as JavaScript:

    // In IE8, this took 282 ms
    // In Chrome 14.0, this took 4 ms
    function f() {
        var sum = 0.5;
        for(i=1; i<=1000000; ++i) sum = sum + i;
        return sum;
    }
    
    var start = new Date().getTime();
    f();
    time = new Date().getTime() - start;
    

提交回复
热议问题