Shane O'Sullivan's technical blog… really ties the room together

Dojo event performance tip

Posted by Shane O'Sullivan on August 23, 2007

When working with the Dojo Ajax Toolkit and using it’s dojo.event package to listen to DOM and custom events, the two most common approaches are:

  1. Listen for an event (or function call) to be triggered on an object, and when it is to run a custom function, e.g.
    var alertFn = function() {alert(“widget is showing”);};
    dojo.event.connect(myWidget, “onShow”, alertFn);
  2. This basically says that when the “onShow” function is called on some widget, called myWidget, run a function that does a simple alert. Of course you can do whatever you like inside this function.

  3. Listen for an event (or function call) to be triggered on an object, and when it is to run a custom function defined in the scope of an object, e.g.
    var myObj = {
    alertFn: function() {alert(“widget is showing”);}
    dojo.event.connect(myWidget, “onShow”,myObj, “alertFn”);

    This is saying that I have an object called “myObj“, which has a function called “alertFn“, and when the “onShow” method on “myWidget” is called, call the “alertFn” function on “myObj“.

I’ve found that when working with Dojo version 0.4.2 and 0.4.3, using the second approach is far far quicker. It turns out that internally, if you simply pass an anonymous function to Dojo, it will add that function to an internal structure and do a brute force search on that internal structure to make sure that this function is unique. This can result in a very significant performance hit – I’ve seen it take up over 50% of the startup time of a page on one of our more JavaScript heavy applications.

So, the conclusion is that if you are dojo.event.connect, which is one of the most useful functions in the toolkit, make sure to use four arguments to the function (approach #2 above), rather than just three (approach #1 above). If necessary, place a simple wrapper around the function as I have shown.
Share this post:digg it|kick it|Email it|bookmark it|reddit|liveIt


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: