Benchmarking the jQuery DOM ready binding

Written by Jakob Løkke Madsen

24. February 2012

After a discussion with a colleague about the pros and cons of using a lot of $(document).ready(function(){ … }) statements across a project, I decided to measure the raw performance of the event binding itself.

Both of us agreed that extensive use of this statement represents a sort of code-smell - that it’s probably a sign that your Javascript needs better structure - and that this, in turn, will probably lead to bad performance in one way or another.

But that set aside, how about the statement itself? Does it incur a performance hit?

Here’s the code I used for testing:

var no_of_bindings = 100;

function bind(){
    for (var i = no_of_bindings - 1; i >= 0; i--){
        $(document).ready(function(){ });
    };
};

console.time("bindings");
bind();
console.timeEnd("bindings");

For IE, I used Firebug Lite, which supports the console.time method. All times are measured in milliseconds.

And here are the results:

Number of bindings: 1 10 100 1000 10000 100000 1000000
Firefox 1 1 5 12 109 1052 4952
Chrome 0 0 0 2 17 160 1936
IE9 0 2 5 16 140 1831 16866
Safari 0 0 1 6 63 872 8739

As it turns out, you need to do an absurd amount of bindings before the performance overhead is worth caring about - even for IE. It might be different for older browsers, of course, but I didn’t feel like bothering with measuring those, since the pattern is probably equal + you have loads of other things dragging you down.

So in conclusion: DOM ready bindings are almost free to do, but you should of course still be conscious about why you are using them.

comments powered byDisqus