Reusing a jQuery object is faster, but always better?

I came across some code at work as follows:

var $divs = $('div'); var $jq = $([1]); $divs.each(function () { $jq.context = $jq[0] = this; // ... do stuff ... }); 

I perf'd higher, and it seems a lot faster than $this = $(this); at the top of the function. Inside the function, the $jq variable has a standard set of typical jQuery methods pushed from it ( .hasClass(), .data(), .find(), ... ), and the code works as intended.

I wonder what the trade-offs are; that is, what do you lose without creating a new object every time? Am I just losing the “story” (ie .pushStack(), .end(), .andSelf(), ... )? Should I do this all the time?

Also, is this a named template? I couldn’t understand all my life how to research this on Google.

+5
source share
1 answer

This seems like crazy micro-optimization. In the basic case, of course, reusing an object is an order of magnitude faster. But the whole point of caching the current object is to save time in subsequent actions; in a grand scheme, it doesn’t matter if you don’t process hundreds of thousands of elements (do not do this.)

What will you lose

  • reasonable area . By storing your object in the outer iteration area, you break the callback closure. The obvious example is that if you console.log($jq) here, all log entries will refer to the same object (the last in the loop) compared to this , which will be unique for each iteration.

  • readability : var $this = $(this) much faster to read / understand than $jq.context = $jq[0] = this .

As for the "story", I don’t see how you lose it here. In any case, you start with a specific object, so any search that you do from there will be written exactly the same.

+1
source

Source: https://habr.com/ru/post/1207256/


All Articles