Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 640
adardesign Avatar asked Jul 12 '11 20:07

adardesign


1 Answers

I think the find() call is what's slowing things down.

The only reason to cache a jQuery object is if you're going to be referencing or manipulating it multiple times. If you're just setting a CSS property and that property's not going to be changed by for the life of the rendered page, then there's no reason to define a cache variable.

like image 80
Adrian J. Moreno Avatar answered Nov 15 '22 21:11

Adrian J. Moreno