Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 938
Flux Avatar asked Dec 19 '13 00:12

Flux


People also ask

Is an empty string undefined?

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 .

How do you know if a function is defined?

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.

How do you check if a string is empty or undefined in JavaScript?

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.

What is an empty function called?

A "noop" or "null function": var noop = function(){}


1 Answers

  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.

like image 191
tckmn Avatar answered Sep 21 '22 19:09

tckmn