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:
tic,for t= 1:1e6, x=x; end,toc %This runs very fast, about 0.07 sec
y=x; tic,for t= 1:1e6, y=x; end,toc %This runs fast, about 0.11 sec
tic,for t= 1:1e6, x; end,toc %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?