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
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.
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 that contains a million 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.
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")