views:

582

answers:

2

I've just recently asked the folloiwng question with regard to jQuery chaning:

http://stackoverflow.com/questions/1286829/is-there-a-preferred-way-of-formatting-jquery-chains-to-make-them-more-readable

A number of people replied with the suggestion that maybe I reduced the amount of chaining within the statement, and instead stored objects in holding variables, which makes sense to me.

However, my understanding is that the objects within a chain are already held on a stack (of sorts), so is the caching/storing of the results in a variable not effectively re-storing it, using more memory?

A comment on one of the posts seemed to indicate that there might not be too much of a performance hit (if any), so I would be happy to cache as suggested if it would be much more readable.

And also, if we are using caching, does this not then start limiting the usefulness of .end() and .andSelf()?

+5  A: 

Objects are generally stored as references - pointers to locations in memory. Two variables both holding the same object don't duplicate all of the object's data - they just both hold pointers to the same location in memory where the actual object data is located. Thus, storing the object in a variable won't have much of a performance hit at all; nothing significant.

Amber
Interesting. So if I cast a number to a string - String(number), would this be a reference as well?
James Wiseman
No. String(123) returns a string literal, not an object - thus there's no reference involved. If you wanted a String object, you'd need `new String(123)` instead, to create a new String object with contents of '123'.
Amber
Good explanation +1
redsquare
Note that new String(123) still returns a literal and there is still no reference involved. Not sure that was clear. Only Objects, Arrays and Functions can be pointers.
mwilcox
@mwilcox: not true. Try the following: `var a = String('123');a.test="blah";alert(a.test);` and then compare it with `var a = new String('123');a.test="blah";alert(a.test);` - you'll see that the former pops up "undefined", while the latter pops up "blah".
Amber
+1  A: 

Adding to @Dav's answer, there are times when storing jquery objects in variables will be a good thing. Classic example:

$('#something div').each( function() {
    $(this).css({'background-color':'#afa'});
    // do some stuff;
    $(this).slideDown('fast');
}

Better way:

$('#something div').each( function() {
    var $this = $(this);
    $this.css({'background-color':'#afa'});
    // do some stuff;
    $this.slideDown('fast');
}

This way you avoid creating jquery objects whenever you call $.

Here Be Wolves