var arr=[];
var k;
for(var i=0;i<5000;i++)
arr[i]=i;
console.time("native loop");
var len=arr.length;
for(var j=0;j<len;j++)
k=arr[j];
console.timeEnd("native loop");
console.time("jq loop");
$(arr).each(function(i,el){
k=el;
});
console.timeEnd("jq loop");
It is generating, 14ms for native loop and 3ms for Jquery each.
I’m using Jquery 1.6.2. If Jquery uses native loop behind the scene, then how come, this is possible??
I would think that it has to do with the scope of your index variable — your
jvariable is a global, which is about the slowest case of variable access. Every time that your loop has to reference j, it needs to check all the way up the scope chain, back to the global object, and then get the variable value from there.I get similar numbers to you in my console (Chrome, OS X — 13-15ms for the for loop, 3-4ms for jQuery).
But, if I do this:
It executes in just 5ms.
The difference in this case is that
jis a function-local variable, available immediately in the first place the JavaScript engine looks for variables.lenis similarly local; the only globals in this case arekandarr.To get even more speed out of this, make k a function-scope variable, and pass in
arras a parameter:Well, that’s a bit too fast now. Maybe arr should be bigger:
That slowed it down a bit.
With a 500k-element array, this code runs in 4ms in the JavaScript console on my machine. At 5M, it takes 36ms.
You should also note that you aren’t using a raw jQuery.each() call — you are first wrapping your array in $(), creating a jQuery object, and then calling .each on that. A fairer test might be to run
That should be pretty close to the timing of the second example above. jQuery adds a bit of overhead; checking the types of its arguments, but after that it runs a pretty tight loop.