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?