var timesTest = 1000;
function empty(){}
console.time('running an empty function');
for( var i=0; i<timesTest; i++ ){
empty();
}
console.timeEnd('running an empty function');
var somethingthatdoesnotexist;
console.time('checking if a function exists');
for( var i=0; i<timesTest; i++ ){
if( somethingthatdoesnotexist ){
somethingthatdoesnotexist();
}
}
console.timeEnd('checking if a function exists');
// results:
// running an empty function: 0.103ms
// checking if a function exists: 0.036ms
在数量较少时,检查未定义的参数要快得多。
一旦测试次数增加,事情就会变得有趣。
// var timesTest = 100000;
// results:
// running an empty function: 1.125ms
// checking if a function exists: 1.276ms
and
// results:
// var timesTest = 1000000000;
// running an empty function: 2096.941ms
// checking if a function exists: 2452.922ms