Take a very simple jQuery plugin boilerplate:
var _defaults = {
foo: false
};
function Plugin( settings ) {
this.opts = $.extend( {}, _defaults, settings );
}
I have a doSomething method that can only run successfully if the option foo is set to true and there are other methods that may doSomething() at a certain point so I had a dilemma on where to place my if statement. First I thought:
Plugin.prototype = {
doSomething: function() {
// Do something that depends on foo
},
method: function() {
...
if ( this.opts.foo ) { this.doSomething() }
},
method: function() {
...
if ( this.opts.foo ) { this.doSomething() }
}
};
But then for the sake of DRYness I decided to do this:
Plugin.prototype = {
doSomething: function() {
if ( this.opts.foo ) {
// Do something that depends on foo
}
},
method: function() {
...
this.doSomething();
},
method: function() {
...
this.doSomething();
}
};
So now methods that may utilize doSomething run the function regardless of it being empty if foo is false.
So my question is, what is a better approach? The second one is shorter but it has to look-up the method everytime even if it’s not necessary just to perhaps run an empty function. So is the first one more efficient?
Oh, and yes, I know probably this is micro-optimization and folks will say don’t worry about it but I’m just curious…
Calling a function will be more inefficient than your first approach.
Have a look at the tests here:
http://geek.michaelgrace.org/2011/02/javascript-performance-hit-calling-function-vs-inline/
They confirm that function calls can be up to 50% slower on some browsers. You can test out your own.