Thursday, 19 September 2013

Doing something is faster than doing nothing in Matlab loop

Doing something is faster than doing nothing in Matlab loop

In the process of analyzing how fast a trivial loop could be, I
encountered this strange phenomenon.
Doing nothing with a variable is much slower than doing something with it.
Of course this is not a real problem as you won't often feel the urge to
write code that does nothing, but this surprised me so I wonder if anyone
understands what is happening and whether this could be a problem in real
situations.
Here is what I found:
for t= 1:1e6, y=x; end %This runs fast, about 0.1 sec
for t= 1:1e6, x; end %This takes over half a second
I tried adding a trivial calculation in the loop to ensure the loop would
not be optimized away but this did not change results.



To summarize, my question is:
What is happening and should I ever worry about it?

No comments:

Post a Comment