× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Why is "this" more effective than a saved selector?

Zach Saucier
Feb 02, 2015
<p>Some of this increase in slowness is because the object reference is already found in memory, so the compiler doesn't have to go looking in memory for the variable</p> <pre><code>$("#bar").click(function(){ $(this).width($(this).width()+100); // Only has to check the function call }); // each time, not search the whole memory </code></pre> <p>as opposed to </p> <pre><code>var bar = $("#bar"); ... bar.click(function(){ bar.width(bar.width()+100); // Has to search the memory to find it }); // each time it is used </code></pre> <p>As zerkms said, dereferencing (having to look up the memory reference as I describe above) has <a href="http://jsperf.com/function-call-vs-closure" rel="nofollow">some but little effect</a> on the performance</p> <p>Thus the main source of slowness in difference for the tests you have performed is the fact that the DOM is not reset between each function call. In actuality, a saved selector performs just about as fast as <code>this</code></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/22596433/Why%20is%20%22this%22%20more%20effective%20than%20a%20saved%20selector?/22596725">Stack Overflow</a>.</p>
comments powered by Disqus