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?
COMPARING NULL, UNDEFINED, EMPTY null !== undefined because one is an object while the other is undefined . The empty string is the “odd one” that will not match with null and undefined .
Use the typeof operator to check if a function is defined, e.g. typeof myFunction === 'function' . The typeof operator returns a string that indicates the type of a value. If the function is not defined, the typeof operator returns "undefined" and doesn't throw an error.
Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.
A "noop" or "null function": var noop = function(){}
http://jsperf.com for more accurate benchmarking and fancy graphs. I made one: http://jsperf.com/empty-vs-check
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With