WHAT: this is a blog where i collect news about the usage of javascript a serious programming language on the client side and server side. WHY: because it seams to be the most ubiquitous language and has functions as first class objects, and closures and ....

Friday, July 18, 2008

Reduce the number of inner function creations and closures

Oft it is easy to create an anonymous function to handle an event or perfrom a little task:

Look at this example:

var b = function (/*array*/a ) {
a.forEach(function(_){ if( _=_.text) alert(_);});
}


The function which perfroms the alert is in javascript an object and created once for the whole array but it is still created each time when b is called.

Functions are objects with a state fromed by a closure.
In this case the closure is not needed, as the function does not use any variable or parameter of b.
The new creation of this function on each call of x is thus just a waste of time and has to be cleaned up by garbage collection.

Wy not create the function once and store the function and reuse it lateron. But where?!

We could use the function object which we store in b.
To reference it we give it a name F
and our anonymous alert function is stored in F.alert_text:


var b = function F () {
a.forEach( F.alert_text = F. alert_text || function(_){ if( _=_.text) alert(_);});
}


It looks almost the same, but this time for each is perfomed with F.alert_text which is set to it's previous value or set to the anonymous function if not yet defined.

When we have a little global update function to extend (X) an object with properties of an other one like this:

var X = function(/*target*/t,/*source*/s){ for ( var p in s ) {t[p]=s[p];} return t; };


we can rewrite the above code to:

var b = X( function F () {
a.forEach( F.alert_text );
},{
alert_text : function(_){ if( _=_.text) alert(_);}
});


This time F.alert_text is even not tested and set to the same vaue, each time when b is called.

Note: this tip is only usefull if the extracted function (here alert_text) is really independent of the state defined by the function calling it. ( here b).

No comments: