Are local variables faster?
I wrote up a very quick experiment to see if this were the case. I tested on Safari 3 (Windows), Opera 9.02, Internet Explorer 7, and Firefox 220.127.116.11. The results are interesting and I’m still trying to understand them:
- In Safari 3 (Windows), using local variables typically takes longer than using globals. However, there is a decent amount of time when the two are exactly equal.
- In Opera 9.02, using globals routinely show up as slower than locals. There are, though, some instances when the two are equal and, every so often, an instance when globals are faster than locals (though this is clearly the least likely to occur).
- In Internet Explorer 7, the two end up equal most of the time. The second most common occurrence is globals being faster than locals. I have seen instances where locals are faster than globals, but it doesn’t happen very often.
- In Firefox 18.104.22.168, global variables are much faster than locals by a factor of at least 3. This was the most surprising to me. Never did the two come close in timing.
I’m wondering if the creation and destruction of local variables contributes to the timing discrepancies in this experiment. Please take a look at the source code and let me know if you see anything that may be skewing these results. Please feel free to play with the experiment and a little bit and let me know what results you come up with.