jQuery Optimization/Best Practices
Asked Answered
F

6

38

Ok saddle up cowboys, because this is going to be a long one. I have been spending the morning going through some of my old code and I'm left wondering about best practices and optimzation. In order to avoid a ride down subjective lane I'll just post some examples with some hopefully easy to answer questions. I will try to keep the examples very simple for ease of an answer and to decrease the likelihood of mistakes. Here we go:

1) Assignment vs jQuery Calls

I understand that when accessing selectors it's generally considered better to assign a selector to a variable rather than make the same call more than once - ex.

$('div#apples').hide();
$('div#apples').show();

vs.

var oranges = $('div#oranges');
oranges.show();
oranges.hide();

Does this same rule apply when referencing jQuery's $(this)? Ex. A simple bit of script to make some data in a table clickable and customize the link.

$('tr td').each( function() {
    var colNum = $(this).index();
    var rowNum = $(this).parent().index();
    $(this).wrap('<a href="example.com/hello.html?column=' + colNum + '&row=' + rowNum +'">'); 
})

vs.

$('tr td').each( function() {
    var self = $(this);
    var colNum = self.index()
    var rowNum = self.parent().index()
    self.wrap('<a href="example.com/hello.html?column=' + colNum + '&row=' + rowNum +'">'); 
});

2) this vs $(this)

Ok so this next one is something that I have wondered about for a long time but I can't seem to find any information on it. Please excuse my ignorance. When does it make sense to call the vanilla js this as opposed to the jQuery wrapped $(this)? It's my understanding that -

$('button').click(function() {
  alert('Button clicked: ' + $(this).attr('id'));
});

Is much less efficient than accessing the DOM attribute of the vanilla this object like the following -

$('button').click(function() {
  alert('Button clicked: ' + this.id);
});

I understand what is going on there, Im just wondering if there is a rule of thumb to follow when deciding which to use.

3) Is more specificity always better?

This one is pretty simple, is it ALWAYS beneficial to be more specific with our selectors? It's easy to see that $('.rowStripeClass') would be much slower than $('#tableDiv.rowStripeClass'), but where do we draw the line? Is $('body div#tableDiv table tbody tr.rowStripeClass') faster still? Any input would be appreciated!

If you've made it this far, thanks for taking a look! If you haven't, :p ​

Flowery answered 12/7, 2010 at 17:38 Comment(0)
H
37

I'll try to answer these as concisely as possible:

  1. Cache it when it's used often, especially in a loop situation, running the same code to get the same result is never a good thing for performance, cache it.

  2. Use this when you only need a DOM element and $(this) when you need the jQuery methods (that wouldn't be available otherwise), your example of this.id vs $(this).attr("id") is perfect, some more common examples:

    • Use this.checked instead of $(this).is(':checked')
    • Use $.data(this, 'thing') instead of $(this).data('thing')
    • Any other case where creating a jQuery object isn't useful basically.
  3. Decending from an ID selector is preferred for performance...how specific do you need to be? That completely depends, in short: be as specific as you need to be.

Haslam answered 12/7, 2010 at 17:46 Comment(3)
Thanks for the insight Nick! As Patricia said, always great answers.Flowery
Based on popularity im going to accept this as the answer. I feel like most of the other answers were very useful as well so I have +1'd where I could!Flowery
Why is $.data(this, 'thing'); better than $(this).data('thing');? Does using $(this) require yet another lookup or something? +1 by the way, great answer!Scullion
I
9

1) Assignment vs jQuery Calls

Does this same rule apply when referencing jQuery's $(this)?

Yes, absolutely. A call to the $ function creates a new jQuery object and with it comes associated overhead. Multiple calls to $ with the same selector will create a new object every time.

2) this vs $(this)

I would say knowing the difference is important because at times it becomes crucial that you don't wrap your objects with jQuery. In most cases, you wouldn't want to do premature optimization and just to keep things consistent, always wrap them with $(this), and preferably cache it in a variable. However, consider this extreme example of an unordered list <ul> that contains a million <li> elements:

$("#someList  li").each(function() {
    var id = $(this).attr('id');
});

A million new objects will be created which will incur a significant performance penalty, when you could have done without creating any new objects at all. For attributes and properties that are consistent across all browsers, you could access them directly without wrapping it in jQuery. However, if doing so, try to limit it to cases where lots of elements are being dealt with.

3) Is more specificity always better?

Not always. It mostly depends on browsers, and again not worth delving into micro-optimizations unless you know for sure that something is running rather slow in your application. For example:

$("#someElement") vs $("#someElement", "#elementsContainer")

It may appear that since we are also provide a context when searching an element by id, that the second query is going to be faster, but it's the opposite. The first query translates to a direct call to the native getElementById(..) while the second one doesn't because of the context selector.

Also, some browsers might provide an interface to access elements by class name using getElementsByClassName and jQuery might be using it for those browsers for faster results, in which case providing a more specific selector such as:

$("#someElement.theClass")

might actually be a hindrance than simply writing:

$(".theClass")
Intromit answered 12/7, 2010 at 18:0 Comment(2)
With respect to your last example, #someElement will always be faster than a class lookup. getElementById() is as fast as it gets, it's a unique lookup, usually against a hash table under the covers. For the other examples, they're valid remarks, but keep in mind they're not equivalent, for example: what if you only wanted to select #someElement if it was within #elementsContainer? In either case, use $("#elementsContainer #someElement") over $("#someElement", "#elementsContainer") for performance, use a context, but not if it's another selector, it's an extra Sizzle call.Haslam
@Nick - #someElement is always the fastest like you said as it translates to getElementById. However, #someElement.someClass is not as it goes to (context || rootjQuery).find( selector ) and not getElementById. Passing a selector string or even an element as context in an id call will always slow things down, so even $("#someElement", $("#elementsContainer")) will be slower than just $("#someElement"). Your point of the two examples not being equivalent is very valid, but this was just to give an example that adding more to the scope will not always help matters.Intromit
S
4

This blog isn't too dated, but it supplies some answers to your questions as well as gives some more info on speeding up your site when using jquery: http://www.artzstudio.com/2009/04/jquery-performance-rules/

One of my favorites is number six which states to limit DOM manipulation. It's always a bad thing to do a .append in a for loop since each time you are appending to the DOM, which is an expensive operation.

Swagerty answered 12/7, 2010 at 17:44 Comment(1)
Awesome awesome blog post. +1 for sure.Flowery
L
4

Up to your questions:

  1. Caching the jQuery object should yield best performance. It will avoid DOM lookups which is what can get slow when performed many times. You can benefit from jQuery chaining - sometimes there is no need for a local variable.
  2. The same goes with $(this) when this is a DOM element. Despite the fact that this is the fastest way to obtain a jQuery object it is still slower than caching. If the vanilla DOM element would suffice - then don't call jQuery at all. The example with the id attribute is excellent - prefer this.id than $(this).attr('id) if you are not going to need $(this)
  3. More specific selectors will decrease the DOM lookup time indeed. However there is indeed a line to be drawn - make the selectors more specific only if you are 100% sure this would improve performance in a noticeable way.
Lander answered 12/7, 2010 at 17:49 Comment(0)
D
3

The only situations you should keep your eye on are loops and events. Because every action you make in one of these will be done in every iteration or on every event.

  1. Assignment vs jQuery Calls

    Your example is not the best. The place where you should save references to jQuery objects are the ones used in loops or events, or which are results of complex queries.

  2. this vs $(this)

    Again in performance critical situations raw dom is better. Other than that you should chose which is shorter or more readable. Surprise, surprise it's not always jQuery.

  3. Is more specificity always better?

    There are more types of specificity which are usually confused by people. One of them is useless which e.g.: a tag name for an id selector tag#id, it will be slower than a simple id. But there is another type when it will be a huge benefit to be specific. Now this type depends on the browser, because the modern ones will sacrifice for the old ones, but it worths the trade-off This happens when you specify a tag for a class tag.class. In IE 6-7 it will be significantly faster than a simple .class, because sizzle can make use of the fast document.getElementsByTagName function. Now another type is when you specify too much ancestors. This will slow things down in every browser. This is because the selector is executed from right to left. The rule to keep in mind: always be the rightmost selector as specific as possible.

Damascus answered 12/7, 2010 at 17:59 Comment(1)
The more I learn the less surprising it is that jQuery is not always the answer :)Flowery
R
1

2013 blog article about the best jQuery practices

Updated answers on your question and even more regarding the best jQuery practices to apply nowadays, this article is dealing with interesting subjects that are really helpful and that you might want to read.

It deals with the subjects asked here and even more: the animate function,jQuery promises, best ways to import jQuery, jQuery events etc. Hope that will be helpful to you!

Rutkowski answered 19/7, 2013 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.