Does using $this instead of $(this) provide a performance enhancement?
Yes, definitely use $this
.
A new jQuery object must be constructed each time you use $(this)
, while $this
keeps the same object for reuse.
A performance test shows that $(this)
is significantly slower than $this
. However, as both are performing millions of operations a second, it is unlikely either will have any real impact, but it is better practice to reuse jQuery objects anyway. Where real performance impacts arise is when a selector, rather than a DOM object, is repeatedly passed to the jQuery constructor - e.g. $('p')
.
As for the use of var
, again always use var
to declare new variables. By doing so, the variable will only be accessible in the function it is declared in, and will not conflict with other functions.
Even better, jQuery is designed to be used with chaining, so take advantage of this where possible. Instead of declaring a variable and calling functions on it multiple times:
var $this = $(this);
$this.addClass('aClass');
$this.text('Hello');
...chain the functions together to make the use of an additional variable unecessary:
$(this).addClass('aClass').text('Hello');
why assign $(this) to a var
The $
function builds a jQuery object from the value(s) passed into it. If you constantly call it over and over again, you're building the same thing over and over again. Many people instead choose to cache the result, so as to avoid repetitiveness.
Should I combine jQuery selectors into variables for better performance?
Here's a JSPerf that you can either use as is or modify to more closely match your specific case:
http://jsperf.com/combined-jquery-selectors
In my browser (Chrome on a Mac), your original version runs about 4% slower than your suggested optimization. On my iPhone using Safari, it's about 6% slower. But on Firefox on my Mac, it's a 14% difference.
So it would appear that your proposed improvement is in fact better.
Selectors and performance
Spencer ,
This is called caching and it is one of the best practices.
when you say
$('#elemId');
It will go and query the DOM everytime , so if you say
var elem = $('#elemId');
elem acts as a cache element and improves performance a lot.
This is manly useful in IE as it has memory leaks promblem and all
ready this document which is really good
http://net.tutsplus.com/tutorials/javascript-ajax/14-helpful-jquery-tricks-notes-and-best-practices/
Is there a performance gain from caching $(this)?
A teeny tiny miniscule imperceptible one, yes. Significant? No.
Every time you do $(this)
, it results in several function calls and a couple of memory allocations. The function calls are neither here nor there (even on IE6, I was surprised to learn), but the memory churn could add up on browsers that don't handle memory management very well. Most modern ones do.
I always save the result to a variable, because I just don't like calling functions and allocating objects needlessly. And it saves typing those parens. :-)
jQuery - Is there an easier way to write this?
I edited @Boaz code and now you get something clean, which i guess can help you also to understand better. I also added some comments.
The jQuery code become
$('#next, #prev').click(function(){
var t = $(this),
current = $('#steps_container').find( '.step:visible' ),
stepGo = ( t.attr( 'id' ) == 'next' ? current.next() : current.prev() );
if ( stepGo.length ) {
current.fadeOut( 'slow', function(){
stepGo.fadeIn( 'slow' );
});
};
return false;
});
Optimizing jQuery code
This might be a bit of an overkill optimization, but this code should work:
$(function() {
$('.allAdmin, .allRemote, .allSupport, .allMisc, .allLogging').change(function() {
$('.' + $(this).attr('class').split(' ')[0].substring(3).toLowerCase()).prop('checked', $(this).prop('checked'));
});
});
If your elements have only one class (nothing like <div class="allAdmin anotherClass">
), you can use this slightly shorter version:
$(function() {
$('.allAdmin, .allRemote, .allSupport, .allMisc, .allLogging').change(function() {
$('.' + $(this).attr('class').substring(3).toLowerCase()).prop('checked', $(this).prop('checked'));
});
});
jQuery Selectors and $(this)
Use .find()
$(this).find(">form>input.inplace_field")
OR
$(">form>input.inplace_field" , this) // Provide a context to search in
JS
$("span#dateofbirth").bind('click', function() {
$(">form>input.inplace_field" , this).blur()
.removeClass("inplace_value")
.datepicker({dateFormat:'yy-mm-dd'})
.addClass("inplace_value")
.focus();
});
You should chain
or cache
the selectors to reduce the times you query the DOM.
Related Topics
How to Close a Dropdown on Click Outside
Arrow Function in Object Literal
How to Animate Scrolltop with Jquery
JavaScript Use Variable as Object Name
Is There a Sleep Function in JavaScript
Handle Url Fragment Identifier (Anchor) Change Event in JavaScript
How to Pass Parameters to a Script Tag
Injecting a Mock into an Angularjs Service
How to Smoothly Scroll to an Element in Pure JavaScript
Sort an Array of Objects Based on Another Array of Ids
What Does $.When.Apply($, Somearray) Do
How to Sort Numbers Correctly with Array.Sort()
Sorting Objects by Property Values