Search code examples
jqueryperformancejsperf

Minimizing jQuery instance vs creating more instances


I started a series of posts on javascript / jQuery optimization and stumbled upon this interesting result.

Why is it that minimizing jQuery objects (by searching from a cached jQuery collection) can be slower then creating more instances of jQuery objects?

I was stunned to see the results of a test i prepared. I always thought that minimizing creating $ instances are slower.

This is what i am used to write, as i cache the parent (i call it "appRoot").

var appRoot = $("#appRoot");
    appRoot.find(".element1").css("color","red");
    appRoot.find(".element2").css("color","blue");

vs

    $(".element1").css("color","red");
    $(".element2").css("color","blue");

See the test results (slightly different scenario). jsperf minimize-jquery-object-creation it turns out that the cached snippet is slower then the uncached snippet.

I am trying to understand why?


Solution

  • You need to consider that your test contains less than 10 divs or other html elements. The reason to write code like in the first example is to make the selector faster, but with the cost of additional method calls. Normaly the selector should be the more expensive of the two by far so the the gain would outweight the loss but with a DOM this small the selector will be very cheap no matter how you write it.

    People often make the misstake of not remembering that a more complex and large DOM will change the bottlenecks of the code. I think jsperf should have some kind of warning about this.