For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?
if ($("#navbar .heading").text() > "") { $("#navbar .heading").hide(); }
and
var $heading = $("#navbar .heading"); if ($heading.text() > "") { $heading.hide(); }
If the selector is more complex I can imagine it's a non-trivial hit.
Caching enhances the performance of the application. Cache your jQuery selectors for better performance. This can be done using the ID as your selector. For example, this caches the selector and stores it in variable.
ID and Element selector are the fastest selectors in jQuery.
It is wasteful to constantly call $( selector )
over and over again with the same selector.
Or almost always... You should generally keep a cached copy of the jQuery object in a local variable, unless you expect it to have changed or you only need it once.
var element = $("#someid"); element.click( function() { // no need to re-select #someid since we cached it element.hide(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With