What is great about jQuery is its simplicity in selecting elements. We all use it here and there, basically everywhere. This simplicity comes with its drawbacks. jQuery traverses through all elements every time we use selectors. So to boost up your jQuery application you should always cache your selections to some variable (if you find yourself using the same selection more than once). In case you are not selecting an element more than once you should not cache your selection by assigning it to some variable.
Here is an example:
var cached = $('.someElement'); cached.addClass('cached-element');
Here are the performance tests:
console.time('test'); for (i = 0; i < 1000; i++) { $('.the').text(i + ' '); } console.timeEnd('test'); // ~260ms console.time('test2'); var the = $('.the'); for (i = 0; i < 1000; i++) { the.text(i + ' '); } console.timeEnd('test2'); // ~30ms
As you can see caching increased performance by nearly 10 times.
I call it "assigning to variable", not "caching" :P
ReplyDeleteThis won't be a problem with 1.3 as Sizzle caches for you! :)
ReplyDeleteActually, it looks like the caching code has been removed because of a performance issue: http://github.com/jeresig/sizzle/commit/40bd422d65391dbdca856d99c92f3551f1e52ea4
ReplyDeleteyes, many young programmers do not know about it.
ReplyDeletejQuery make every thing simple and usable, but every javascritp programmer must profile any code line. it is very important to know how jquery is works besides of what jquery does.
Thanks and sorry for my poor english
I'd recommend prefixing your variables with a $ for jQuery collections. This is somewhat of a common convention to denote that that variable is in fact a jQuery collection. For example when I'm inside an event handler I often have the following line of code: var $this = $(this);
ReplyDeleteYou keep using that word, I do not think it means what you think it means...
ReplyDelete"Assigning to javascript variable" is not "Caching".
@Antoine, @Anonymous, I know what caching and assigning to a variable is. But you have to agree, that it's a great title for the post :)
ReplyDeletePS. One could actually argue that keeping randomly accessed objects, that tend to be time or resource consuming, in a variable is caching in a sense...
While this is great and definitely gives a performance boost on almost anything (even if selecting by IDs) you will also need to keep in mind that it does infact "cache" items. If your DOM changed since the last variable definition you will need to update that definition if the selector would now get different items. Just a heads up.
ReplyDeleteIts really nice.My most interesting part is Testing console method.Its really awesome.
ReplyDelete