Created
September 18, 2011 10:12
-
-
Save srikumarks/1224945 to your computer and use it in GitHub Desktop.
Test functions to show that accessing Math as a global is much slower than if it were local.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f1(N) { | |
var i, sum = 0; | |
for (i = 0; i < N; ++i) { | |
sum += Math.sin(i); | |
} | |
return sum; | |
} | |
function f2(f) { | |
return function (N) { | |
var i, sum = 0; | |
for (i = 0; i < N; ++i) { | |
sum += f(i); | |
} | |
return sum; | |
}; | |
} | |
function f3(Module) { | |
return function (N) { | |
var i, sum = 0; | |
for (i = 0; i < N; ++i) { | |
sum += Module.sin(i); | |
} | |
return sum; | |
}; | |
} | |
// f(N) is run a few times, timed and some stats are | |
// returned as an object. | |
function timeit(f, N) { | |
var start, stop, dt; | |
var worst = 0, best = 1000 * 3600, mean = 0, sigma = 0; | |
var i, M = 7; | |
for (i = 0; i < M; ++i) { | |
start = Date.now(); | |
f(N); | |
stop = Date.now(); | |
dt = stop - start; | |
best = Math.min(best, dt); | |
worst = Math.max(worst, dt); | |
mean += dt; | |
sigma += dt * dt; | |
} | |
mean /= M; | |
sigma /= M; | |
return { best: best, worst: worst, mean: mean, spread: Math.sqrt(sigma - mean * mean) }; | |
} | |
Intel(R) Core(TM)2 Quad CPU Q6600 @ 2.40GHz 4GB RAM Windows Vista
N = 100M; 23 sec in FF 6.0.2 (f1local)
N = 100M; 17 sec in FF 6.0.2 (f2local)
N = 100M; 28 sec in Safari 5.1 (7534.50) (f1local)
N = 100M; 13 sec in Safari 5.1 (7534.50) (f2local)
N = 100M; 45 sec in Chrome 14.0.835.163 beta-m (f1local)
N = 100M; 15 sec in Chrome 14.0.835.163 beta-m (f2local)
(Thanks Bharat!)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Macbook Air 1.7GHz Core i5 / 4GB / Lion
N = 100M and reporting only 2 significant figures
Chrome [15.0.849.1 dev]: f1local = 23 secs, f2local = 13 secs
Safari [5.1 (7534.48.3)]: f1local = 8.6 secs, f2local = 8.6 secs
Firefox [6.0]: f1local = 13 secs, f2local = 12 secs