Local Variables take 7x longer to access than global variables?
Posted
by ItzWarty
on Stack Overflow
See other posts from Stack Overflow
or by ItzWarty
Published on 2010-04-20T21:48:17Z
Indexed on
2010/04/20
22:13 UTC
Read the original article
Hit count: 186
I was trying to benchmark the gain/loss of "caching" math.floor, in hopes that I could make calls faster.
Here was the test:
<html>
<head>
<script>
window.onload = function()
{
var startTime = new Date().getTime();
var k = 0;
for(var i = 0; i < 1000000; i++) k += Math.floor(9.99);
var mathFloorTime = new Date().getTime() - startTime;
startTime = new Date().getTime();
window.mfloor = Math.floor;
k = 0;
for(var i = 0; i < 1000000; i++) k += window.mfloor(9.99);
var globalFloorTime = new Date().getTime() - startTime;
startTime = new Date().getTime();
var mfloor = Math.floor;
k = 0;
for(var i = 0; i < 1000000; i++) k += mfloor(9.99);
var localFloorTime = new Date().getTime() - startTime;
document.getElementById("MathResult").innerHTML = mathFloorTime;
document.getElementById("globalResult").innerHTML = globalFloorTime;
document.getElementById("localResult").innerHTML = localFloorTime;
};
</script>
</head>
<body>
Math.floor: <span id="MathResult"></span>ms <br />
var mathfloor: <span id="globalResult"></span>ms <br />
window.mathfloor: <span id="localResult"></span>ms <br />
</body>
</html>
My results from the test:
[Chromium 5.0.308.0]:
Math.floor: 49ms
var mathfloor: 271ms
window.mathfloor: 40ms
[IE 8.0.6001.18702]
Math.floor: 703ms
var mathfloor: 9890ms [LOL!]
window.mathfloor: 375ms
[Firefox [Minefield] 3.7a4pre]
Math.floor: 42ms
var mathfloor: 2257ms
window.mathfloor: 60ms
[Safari 4.0.4[531.21.10] ]
Math.floor: 92ms
var mathfloor: 289ms
window.mathfloor: 90ms
[Opera 10.10 build 1893]
Math.floor: 500ms
var mathfloor: 843ms
window.mathfloor: 360ms
[Konqueror 4.3.90 [KDE 4.3.90 [KDE 4.4 RC1]]]
Math.floor: 453ms
var mathfloor: 563ms
window.mathfloor: 312ms
The variance is random, of course, but for the most part
In all cases [this shows time taken]:
[takes longer] mathfloor > Math.floor > window.mathfloor [is faster]
Why is this? In my projects i've been using var mfloor = Math.floor
, and according to my not-so-amazing benchmarks, my efforts to "optimize" actually slowed down the script by ALOT...
Is there any other way to make my code more "efficient"...? I'm at the stage where i basically need to optimize, so no, this isn't "premature optimization"...
© Stack Overflow or respective owner