2

Possible Duplicate:
Caching $(this) in jQuery is a best practice?

I am curious, within the same function, when $(this) is called multiple times does it incur additional overhead for constructing the jQuery object in the subsequent calls? In other words, is $(this) cached the first time it's called? If not, would it be a better practice to store $(this) in a variable and use that variable when $(this) is needed subsequently?

Community
  • 1
  • 1
tamakisquare
  • 16,659
  • 26
  • 88
  • 129
  • 2
    @neoascetic: +1 Caching is good. As seen in this test: http://jsperf.com/this-vs-cached-this – Nope Aug 03 '12 at 00:08

5 Answers5

4

$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

so basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

http://www.learningjquery.com/2007/08/what-is-this

good figures: http://jsperf.com/jquery-this-vs-this-vs-chain/2

You usually use var $this = $(this); to avoid creating a new jQuery object more often than necessary. In case of the code below you only create one object instead of two/four. It is completely unrelated to chainability.

this in javascript (usually) represents a reference to the object that invoked the current function.

Generally the purpose of storing $(this) in a local variable is to prevent you from calling the jQuery function $() multiple times, caching a jQueryized this should help efficiency if you have to use it multiple times.

$ is simply a valid variable name character and is used as the first character of a variable name usually to queue the programmer that it is a jQuery object already (and has the associated methods/properties available).

$this vs $(this) in jQuery

Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
  • 1
    +1 for mentioning the creation of a new jQuery object for every call. I added a little performance test as well which shows an interesting difference when not caching `this`. http://jsperf.com/this-vs-cached-this – Nope Aug 03 '12 at 00:07
  • @FrançoisWahl Oh wow nic e `:)` you sire are a Legend! – Tats_innit Aug 03 '12 at 00:08
2

I've seen this construct used quite often:

var someFunc = function () {
    var that = $(this);
    // you could also cache like var $this = $(this);

    // do stuff here...
};

Each time you call $() there would be some overhead in making the call but not much. I don't think it would be noticeable if you didn't cache $(this). See SO entry on jquery cache of $(this)

Community
  • 1
  • 1
sinemetu1
  • 1,726
  • 1
  • 13
  • 24
  • There is quite a lot of overhead when calling `$(this)` multiple times compared ot caching it first, i.e: `$this = $(this)` as you can see on this performance test: http://jsperf.com/this-vs-cached-this – Nope Aug 03 '12 at 00:02
  • 1
    @FrançoisWahl You're exaggerating the overhead. For most applications you would never notice whether this is cached or not. See AceCorban's answer to this question. – sinemetu1 Aug 04 '12 at 00:05
  • You are correct off course and I would never worry about micro-optimization starting a new project unless I have to, however, something as simple as caching values is not that hard to make good practise and get used to. That it optimizes your code is a bonus. Seeing not caching is about 60ish% slower than caching in the above test I would say, caching is a good habit to get into. It all adds up and specially with mobile apps becoming more and more popular and jQuery is also used in some of those a good habit to have can save you some re-coding later. – Nope Aug 04 '12 at 00:11
2

Every time the expression $(this) is evaluated, the jQuery factory function is invoked, resulting in a new jQuery instance. However, the performance penalty of this process is negligible. I once calculated that it takes only a few micro-seconds (millionth of a second).

I, personally, don't worry about having $(this) multiple times within a function body. Caching the jQuery instance (var $this = $(this);) is an option, but I don't do it. (I happen to find the $this name ugly, compared to $( this ), and I understand that most people don't agree with me here.)

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • In the majority of cases `$(this)` is not used often enough within a method to notice a difference. This test I created though shows if you call `$(this)` a few times compared to caching it, the difference is quite large. http://jsperf.com/this-vs-cached-this – Nope Aug 03 '12 at 00:04
  • @FrançoisWahl The *relative* difference is significant. However, the *absolute* difference is negligible. On my machine in Firefox, the fist test takes 29 micro-seconds, and the second test 64 micro-seconds. So, one `$(this)` takes about 4 micro-seconds. – Šime Vidas Aug 03 '12 at 00:21
  • You are correct that the execution times are minor (Think they are milliseconds though not microseconds). I'm merely pointing it out as the un-cached version executed about 68% slower in average. This is in % terms a huge difference (regardless of the total time). In addition caching selectors which are re-used is in general good practise and taking `Tats_innit` point into account prevents unnecessary object creation. I also don't think not using something cause it may look `ugly` is the best way to go. – Nope Aug 03 '12 at 00:51
2

I did a quick test to see if there is added overhead to constructing a jQuery object using the $:

var start = (new Date).getTime();
for(var i=0; i<1000000; i++)
{
   var testClass = $("#testDiv").attr("class");
}
var end = (new Date).getTime();
alert(end-start);

all I'm doing here is running the code 1,000,000 times to see how long it takes to store the class of a jQuery object on the page to a variable. It took about 4.286 seconds. I then modified it to reference an already stored object:

var start = (new Date).getTime();
var testDiv = $("#testDiv");
for(var i=0; i<1000000; i++)
{
   var testClass = testDiv.attr("class");
}
var end = (new Date).getTime();
alert(end-start);

This one only took 1.254 seconds. While this is not exactly what you are asking, it does highlight that the process of generating a jQuery object takes more time than referencing something from an already generated object.

That said, the difference will likely be negligible for most applications.

AceCorban
  • 2,023
  • 1
  • 15
  • 15
0

When $(this) is called, it has to be called from within an already instantiated object. $(this) is just a reference to that object, and therefore, the overhead should be minimal.

I could be wrong, but please correct me if so.

Jeremy Gehrs
  • 413
  • 6
  • 17
  • I don't think what you said is right. `this` is the reference to the DOM object. And `$(this)` constructs the corresponding jQuery object. – tamakisquare Aug 03 '12 at 23:00