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

  1. In Chrome, f1(N) takes about twice as much time as f2(Math.sin)(N) which is comparable in speed to f3(Math)(N).
  2. The functions don't differ much in speed on Safari, which runs all of them at around 2x speed compared to the f1(N) in Chrome.

@srikumarks
Copy link
Author

Original post on this performance characteristic of V8 - https://plus.google.com/102694714835839603248/posts/i9dahgLDs9w

@srikumarks
Copy link
Author

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

@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