Which is faster? Running an empty function or checking an undefined function?

I wrote code where the function passed as an argument can sometimes be undefined. Being curious about this as a "practice", I wondered what is actually faster? Providing an empty function or checking a function if the argument was undefined?

I tried the following test. The answer was very unexpected!

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 the undefined argument is much faster.

Things get interesting after the test time 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 grows, running an empty function becomes a little faster marked.

I have not tried to talk about this on the chart yet, but I'm curious about this behavior. Does anyone know why this is? How does this affect things in real world code?

+7
performance optimization javascript function undefined
source share
1 answer
  • http://jsperf.com for more accurate reference and graphic plots. I did one: http://jsperf.com/empty-vs-check

  • This is micro optimization. NOBODY WILL NEVER NOTIFY DIFFERENCE. There the difference is less than half a second for a billion iterations, which will never happen. Do what you think is more readable; don't worry about performance.

+14
source share

All Articles