Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing a jQuery object is faster, but is it always better?

I ran 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 the above, and it seems much faster than having $this = $(this); at the top of the function. Inside the function, the $jq variable has a standard assortment of typical jQuery methods called off of it (.hasClass(), .data(), .find(), ...), and the code works as intended.

I'm wondering what the tradeoffs here are; i.e. what do you lose by not constructing a new object each time? Am I just losing the "history" (i.e. .pushStack(), .end(), .andSelf(), ...)? Should I be doing this all of the time?

Also, is this a named pattern? I couldn't for the life of me figure out how to research this on Google.

like image 798
Impirator Avatar asked Nov 10 '22 22:11

Impirator


1 Answers

This strikes me as an insane micro-optimization. In the basic case, sure, it's an order of magnitude faster to reuse the object. But the whole point of caching the current object is to save time in subsequent actions; in the grand scheme it won't matter unless you are processing hundreds of thousands of elements (don't do that.)

What you lose

  1. sane scope: By storing your object in the outer scope of the iteration, you are breaking the closure of the callback. The obvious example is that if you console.log($jq) here, all of the log entries will refer to the same object (the last one in the loop,) versus this which will be unique to each iteration.

  2. readability: var $this = $(this) is a lot faster to read/comprehend than $jq.context = $jq[0] = this.

Regarding "history", I don't see how you'd lose any here. In either case you're starting with a specific object, so any searching you do from there will be recorded just the same.

like image 149
Mathletics Avatar answered Nov 15 '22 08:11

Mathletics