Basically the markup we’re interested in looks like that:
There is a button, an item list and a wrapping
div element. Easy.
Well, now you want to add the ability to perform another action if a list contains at least three items. So you update your markup by adding it another button:
And you update your code accordingly:
Ok, that’s enough code for now. You can test the result here, to have a better vision of what it does (just save the file on your machine and open it in your browser).
The vanilla code is about 75 times faster than the jQuery code.
From where does this slowness come from? With jQuery you are used to write selectors each time you want to manipulate the DOM. That’s easy to write but finding the elements matching a selector means traversing whole or part of the document tree, checking if each node matches the selector criterias or not. If you look better at the code you’ll find a selector which is very time consuming:
'ul li' (line 12). This selector is not complex but has a whitespace. Each whitespace dramatically slows down DOM search. We can optimize a bit the code by removing this selector and just counting the children of the
ul element. Just doing that divides the execution time by about 5:
Now the jQuery code is only about 15 times slower than the vanilla code. We can optimize further the jQuery code, for example by using the
children method instead of
find but the gain would be marginal and the code would be more tightly coupled to the markup, which is a bad thing. We’ll soon explain in more details why that’s such a bad thing.
All the code used in this post (including the benchmark) is available on GitHub.
What should you remember of this first post putting jQuery to the test to build web applications?
- jQuery is not so fast, using it at large scale may dramatically slow down your application ;
- A minor change on a selector may have a significant impact on its performance.
In the next post we’ll see that as well as being slow, jQuery does not add so valuable things to your code…