~ ajax ~


JavaScript performance optimization, take 1

For the last several months, Mike and I have been working on a new project, which is nearing closed beta. That means we need to start battening down the hatches, and today was the day to start tackling client-side JavaScript performance.

I’ve actually done quite a bit of performance work in my life, but not with JavaScript, so I though I’d take some notes along the way.

Firebug is your friend

In my mind, there are really three ways to a significant dent in performance:

  1. Find bad algorithms and replace them with fast ones
  2. Find code that doesn’t actually have to be called and skip it.
  3. Optimize the code that gets called most often

And you really can’t do any of the three without a profiler. You might think you know what the problem is, but you won’t know until you profile it. In my case, I started out thinking that I had event listeners hanging around that weren’t letting go of their events, but the profiler (in this case, Firebug) told me I was completely wrong.

To get started profiling in Firebug, go to the console tab, press the ‘profile’ button, do some stuff, and hit the ‘profile’ button again. That’s it.

You’ll then be presented with data that looks like this:


For my money, the two most important columns are ‘own time’ and ‘time’. ‘time’ is the total time spent in a function including any functions that are called by that function, and ‘own time’ is the same thing minus the time taken up by other functions.

Problem: $$(‘.class’) can be SLOW!

I created a test where I did the same UI gesture 8 times, and this is what I discovered. Looking at ‘own time’ told me that most of my time was going to DOM traversal via the $$ function.

Looking at ‘time’ told me that the methods responsible for calling $$ were all central functions that were called in many places throughout my code, so it was worth making them as efficient as possible before figuring out whether there was a way to avoid calling some of them altogether.

Phase 1 — replacing traversals of the entire DOM tree (via $$) with smaller traversals

Roughly speaking, this corresponds to strategy (3).

What total time %delta
from prev
from base
Baseline 2812ms
Replace $$(‘.class’) by $(‘section’).getElements(‘.class’) in critical sections 2345ms 20% 20%
Chage getElements(‘.class’) to getElements(‘div.class’) in critical sections 2094ms 12% 34%
Found more places to do the above optimizations 1723ms 22% 63%
Replaced getElements() with getChildren() where possible 1641ms 5% 71%

Along the way, I tried all sorts of other optimizations, but none of them yielded much benefit. Now that I was reaching the point of diminishing returns, it was time to see if there were chunks of code I could safely skip.

Phase 2 — skipping handler functions when possible

I knew that there was almost certainly code I was running that could be skipped (strategy 2). Why?

I find that when writing UI code, it is often easier to use brute force to make sure that everything is working consistently. For example, if an AJAX call updates a certain part of the screen, it is often easier to blow away all event handlers from everything and re-add them where needed, rather than just patching up event handlers for the portion of the screen that was updating.

My rationale is that you can always fix this at the end. And well, it was now time to pay the piper.

My test case involved doing the same UI gesture 8 times. And most of the time was going to the following functions:

add_panel_handlers_if_needed(): 8 times
add_content_handlers(): 16 times
add_panel_handlers(): 8 times
actually_do_drag_cleanup(): 8 times
remove_content_handlers(): 24 times
fix_detail_handlers(): 8 times
handle_click(): 8 times
fix_toggle_rte_handlers(): 8 times
add_drag_handlers_and_start(): 8 times
add_insert_handlers(): 8 times

You can see that some functions are being called 8 times and some were being called 24 times. As it turns out, this was just due to programmer laziness. By adding a few checks, some of those redundant calls could be safely avoided.

The other thing that was causing extra work is that only certain interactions caused screen updates that needed event handlers to be reattached. By writing some code to check for that, I was able to avoid many of these calls altogether.

What total time %delta
from prev
from base
Baseline 2812ms
End of phase 1 1641ms 71% 71%
Remove redundant calls to remove_content_handlers and add_content_handlers 1389ms 18% 102%
Skip certain fixup calls when content is determined not to have changed 1073ms 29% 162%

(P.S. there is some small part of my brain that tells me that instead of manually worrying about these event handlers, I should just bite the bullet and switch to JQuery. But I’m not there yet.)


So, what’s the moral? First off, doing $$(‘.class’) is slow. Second, large performance boosts usually come from a combination of skipping code that doesn’t have to run and optimizing the code that does. This was no exception.

One more thing. I just have to say that Firebug is amazing. I expected it to have trouble giving useful timings in the face of inconsistent UI gestures and garbage collection, but it did the “right thing”, which many desktop profilers don’t manage to do. If I had one wish, I wish I could get it to bundle up calls from specified library files and allocate the time spent in them to the calling function.

Ok. Back to more optimizing.


Layering Flex over AJAX and collaborating with data services — whoa!

Christophe just posted an example of how to layer Flex over AJAX to do video chat and shared whiteboard as an overlay to Google Maps. You could use this to draw a route on a map for someone else to see, for example.

I think my head is going to explode.



Some personal thoughts on the Flex/AJAX Bridge…

Before moving to the Flex project, I ran engineering for the HTML tools division at Macromedia. Back then, we thought a lot about advanced DHTML techniques, including the technique of using XMLHTTPRequest to update portions of a page locally, which has since come to be called AJAX.

As you can see from my posts, I eventually ended up moving to Flex. AJAX is wonderful and has its share of strengths, but I find working with Flex to be more fun for me personally. Flex is a great way to put together richer and more complex front ends. It has a runtime that is consistent across browsers, and an object model that is designed from the ground up to support networked application UIs.

I’m still a big fan of AJAX. I believed in it way back when, and I believe in it now. But Flex can do a lot that would be difficult in AJAX, both visually and in terms of data connectivity.

I’m quite curious to see how people use the two together. I’m convinced that some of the raw building blocks inside of Flash/Flex (e.g., binary sockets) have a lot to add to the AJAX puzzle.

P.S. In my last post, I mistakenly called this the Flex/ActionScript Bridge, which is obviously much less interesting. :-) Thanks to Robert Penner for pointning this out to me.


FAB – Flex / AJAX bridge

FAB – Flex/AJAX Bridge – is a library created by Ely Greenfield, who is a good friend and Flex Architect.

FAB lets you control Flex applications using JavaScript. Method calls just work, and getters and setters are converted to method calls (because browsers don’t support getters and setters yet).

You can even attach event listeners from JavaScript and pass function objects back and forth. For example, you can create an MXML file with a button in it and drive all of the logic from within your HTML/JavaScript.


<mx:Application xmlns:mx=”http://www.macromedia.com/2005/mxml”>
    <fab:FABridge xmlns:fab=”bridge.*” />
    <mx:Button id=”okButton” label=”OK” />


function init()
    var flexApp = FABridge.flash.root();
    flexApp.okButton().addEventListener(“click”, handleClick);

function handleClick(event)
    // handle the click event here.

You can read more about it on Ely’s blog, which I predict will be worth reading.



MXML text completion control v. 0.5 (aka down with combo boxes!)

I’ve always been frustrated by the way HTML applications use pull down menus. How many times have you had to pick a country out of a huge pull down menu? Do you use the mouse to scroll down to the country? What about using the keyboard? You have to keep hitting the same key over and over. Neither approach is easy.

Meanwhile, text fields that offer completion hints are starting to become standard for Flex and AJAX applications. Typicaly, these are used to let you quickly pick things that you’ve already typed into the box. They are not used for picking, say, a country from a list of countries.

I believe text input fields that offer hints for possible completions should be used instead of combo boxes 95% of the time. Down with combo boxes!

1) When you want to use the mouse, it is just as simple.
2) When you want to use the keyboard, it gives you better feedback on what you have typed already.
3) It gives you an obvious affordance to “start over” when you’ve made a typo.
4) It gives you more immediate feedback.

Here is a relatively simple version of a text completion control for MXML. Unlike most versions of this type of control, this is also optimized for the above case: picking from a list of predefined strings.

[Sample removed. Please download the new version instead]

When you want to pick from a list of predefined strings, just supply the list of all strings as the dataProvider of the control (just like how ComboBox works), and set the “mustPick” flag to true.

Let me know what you think. Are there bugs? Do you think the heuristics are wrong? Is this a good idea in general?

P.S. I’ve also had to include some other random classes as part of this. I plan on officially distributing these classes and other classes once they are more baked.