Skip to content

Instantly share code, notes, and snippets.

@wankdanker
Created March 2, 2012 16:15
Show Gist options
  • Save wankdanker/1959392 to your computer and use it in GitHub Desktop.
Save wankdanker/1959392 to your computer and use it in GitHub Desktop.
Benchmark javascript callback functions - anonymous vs named
//Benchmark calling a function passing it an anonymous function vs passing it a named function
//
var iterations = 100000;
function testAnon(fn) {
console.time('test-anonymous-function');
for (var x = 0; x < iterations; x++) {
fn(function () {});
}
console.timeEnd('test-anonymous-function');
}
function testNamed(fn) {
console.time('test-named-function');
for (var x = 0; x < iterations; x++) {
fn(doNothing);
}
console.timeEnd('test-named-function');
function doNothing() {};
}
for (var y = 0; y < 5; y++) {
testAnon(function () {});
}
for (var y = 0; y < 5; y++) {
testNamed(function() {});
}
//Benchmark calling array.forEach() passing it an anonymous function vs passing it a named function
//
var iterations = 1000000;
var ary = [0,1,2,3,4,5,6,7,8,9];
function testAnon() {
console.time('test-anonymous-function');
for (var x = 0; x < iterations; x++) {
ary.forEach(function () {});
}
console.timeEnd('test-anonymous-function');
}
function testNamed() {
console.time('test-named-function');
for (var x = 0; x < iterations; x++) {
ary.forEach(doNothing);
}
console.timeEnd('test-named-function');
function doNothing() {};
}
for (var y = 0; y < 5; y++) {
testAnon();
}
for (var y = 0; y < 5; y++) {
testNamed();
}
//Benchmark calling process.nextTick passing it an anonymous function vs passing it a named function
//
var iterations = 100000;
function testAnon() {
console.time('test-anonymous-function');
for (var x = 0; x < iterations; x++) {
process.nextTick(function () {});
}
process.nextTick(function () {
console.timeEnd('test-anonymous-function');
});
}
function testNamed() {
console.time('test-named-function');
for (var x = 0; x < iterations; x++) {
process.nextTick(doNothing);
}
process.nextTick(function () {
console.timeEnd('test-named-function');
});
function doNothing() {};
}
for (var y = 0; y < 5; y++) {
testAnon();
}
for (var y = 0; y < 5; y++) {
testNamed();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment