Designing the Front-End
Minimize jQuery object creation
Willing to optimize apps to run the fastest posible, developers can sometimes asume (mostly after reading posts amateur developers write) that some optimizations are really better practices.
But unfortunately sometimes it might even slower your app.
sometimes these optimization’s are just for edge cases, (for instance only where there are 1000′s of nodes to manipulate)
It is very common to see code like this, where a new jQuery instance object ($) is created for every set of elements:
$("div").bind("click", function(){
$("#otherDiv").toggle();
})
Each time you call the $() you create a new instance of jQuery.
You can get away with creating as little as a few jQuery Object’s
Just start off with one jQuery instance.
Here is how we can optimize our javascript.
// define one root element
var appRoot = $("#appRoot");
appRoot.find(".someElement").bind("click", function(){
appRoot.find("#otherDiv").toggle();
});
Here he have one root element and we keep on looking (finding) from that root element.
But…
After making a few jsperf tests it turns out that it is not true. It is actually much slower.
See the stackoverflow thread for a detailed explanation.
Here’s an excerpt of the answer:
You need to consider that your test contains less than 10 divs or other html elements. The reason to write code like in the first example is to make the selector faster, but with the cost of additional method calls. Normaly the selector should be the more expensive of the two by far so the the gain would outweight the loss but with a DOM this small the selector will be very cheap no matter how you write it.
| Print article | This entry was posted by adardesign on July 4, 2011 at 5:44 pm, and is filed under Uncategorized. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 6 months ago
Now we know who the sensible one is here. Great post!
about 3 weeks ago
It’s really a nice and helpful piece of information. I’m glad that you shared this helpful information with us. Please keep us up to date like this. Thanks for sharing.