Search code examples
javascriptjquerychainingperformance

Can it be disadvantageous to store jQuery objects in a variable?


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

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()?


Solution

  • 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.