| >> But if someone prefers iterative solutions, or that's all they know, why can't R
make them just as fast as the vectorised versions? R is interpreted and dynamically typed, so when you declare a variable, the
interpreter has to do some bookkeeping to figure out the type of the variable,
allocate memory for it and so on. If you write a loop by hand, the interpreter has to do this bookkeeping once for
each iteration. If you write your code in vectorised form, the interpreter can sort out the
bookkeeping once and then hand over to the lower-level code (C or Fortran) the
vectorised functions are interpreted in. This can also be further optimised to take advantage of processor vector instructions, parallel processing etc. So I'm afraid we can't have our pie and eat it. If we want an interpreted
language with somewhat intuitive notation, then it has to have crappy slow
loops. If we want a language with fast loops we have to rely on C or Fortran and
forget about vectorised notation. |
Unless you're Julia, JavaScript or Lua with a fiendishly clever virtual machine. Look at the benchmark figure here: http://julialang.org/