Created
November 29, 2010 19:02
-
-
Save jmar777/720379 to your computer and use it in GitHub Desktop.
Quick test for verifying that the "fast case" in EventEmitter.prototype.emit is warranted
This file contains hidden or 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
// dummy func | |
function noop() {} | |
// optimized via if/else | |
function testIfElse() { | |
var len = arguments.length; | |
if (len === 1) { | |
noop(arguments[0]); | |
} else if (len === 2) { | |
noop(arguments[1]); | |
} else { | |
noop.apply(null, Array.prototype.slice.call(arguments, 0)); | |
} | |
} | |
// optimized via switch | |
function testSwitch() { | |
switch (arguments.length) { | |
case 1: | |
noop(arguments[0]); | |
break; | |
case 2: | |
noop(arguments[1]); | |
break; | |
default: | |
noop.apply(null, Array.prototype.slice.call(arguments, 0)); | |
} | |
} | |
// no optimizations | |
function testNeither() { | |
noop.apply(null, Array.prototype.slice.call(arguments, 0)); | |
} | |
// test cases | |
var tests = [ | |
[testIfElse, ['test']], | |
[testIfElse, ['test', 'test']], | |
[testIfElse, ['test', 'test', 'test']], | |
[testSwitch, ['test']], | |
[testSwitch, ['test', 'test']], | |
[testSwitch, ['test', 'test', 'test']], | |
[testNeither, ['test']], | |
[testNeither, ['test', 'test']], | |
[testNeither, ['test', 'test', 'test']] | |
]; | |
console.log('Running tests...\n'); | |
// run tests | |
tests.forEach(function(test) { | |
var func = test[0], | |
args = test[1]; | |
console.log(func.name + '(', args, ');'); | |
var i = 0, start = Date.now(); | |
for (; i < 5000000; i++) { | |
func.apply(null, args); | |
} | |
console.log(Date.now() - start + '\n'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment