In R, apply() is NOT faster than a loop!!
I don't know where I pick up this perception about apply() being faster than a loop in R. For a long time, I always think that apply() runs a function (for example, mean()) on a data structure (row or column) in a single shot. So take the mean of each row in the same time. And a loop does it n.row or n.column times. So assuming running a single shot of apply() does not affect too much computing power, I thought apply() should at most n.row or n.column times faster than a loop.
But I am WRONG! In R, apply() is NOT faster than a loop!!
Here is a small simulation I did to test the speed of the two functions. After 1000 simulation, on average, apply() consums twice more system time than a loop does. I thought maybe it is because I did not have two equivalently competing code of apply() and a loop. So I do some search on Rseek.org. Here is the result.
According to Professor Brian Ripley, "apply() is just a wrapper for a loop." The only advantage for using apply() is that it makes your code neater!
Bummer! I had it wrong for a long time.
14 hours ago