What is faster? Running an empty function or checking if function is undefined? [closed]

半世苍凉 提交于 2019-12-21 04:21:15

问题


I was writing some code where a function being passed in as an argument might sometimes be undefined. Being curious about this as bad 'practice', I wondered what is actually faster? Giving an empty function, or having the function check if the argument was undefined?

I did the following test to try. The answer was very surprising!

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

At low numbers, checking for undefined argument is much faster.

Things get interesting once the times tested increases.

// 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 

As the number of tests grew, running a blank function becomes a bit faster by a margin.

I haven't tried plotting this out on a graph yet, but I'm curious as to this behavior. Does anyone know why this is? How does this affect things in real world code?


回答1:


  1. http://jsperf.com for more accurate benchmarking and fancy graphs. I made one: http://jsperf.com/empty-vs-check

  2. This is micro-optimization. NOBODY WILL EVER NOTICE A DIFFERENCE. There's a difference of less than a half a second for a billion iterations, which will never happen. Do what you think is more readable; don't worry about performance.



来源:https://stackoverflow.com/questions/20671498/what-is-faster-running-an-empty-function-or-checking-if-function-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!