Skip to content

Instantly share code, notes, and snippets.

@srikumarks
Created September 18, 2011 10:12
Show Gist options
  • Save srikumarks/1224945 to your computer and use it in GitHub Desktop.
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.
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) };
}
@srikumarks
Copy link
Author

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