Dryadwoods
Dryadwoods

Reputation: 2929

Javascript For loop VS JQuery Each: strange result

I've read several questions / articles about this subject and I tested in my solution that the same block of code using for is most of the times faster than each.

However my question is related to the fact than in my page where I've around 30 "loops" the starting results using each were around 5300ms (average) with max value of 5900ms and minimum of 4800ms.

And after I've changed them to for and the end result surprisingly is slower, takes more time as the previous average (and never got lower than 4800ms and got even higher than 6000ms)..... but when I place console.time('Time') console.timeEnd('Time') in each single "loop block" I get the expected result (FOR is faster).

How is it possible that the global "time" is SLOWER using for than each?

Could please you point me some possible reasons?

P.S.- The full source-code is huge and the important part here is that the only change is: loops each converted to for.

Sample used for the For loop

var l = list.length;  
for (var i=0;i<l; i++) {  

}

Sample used for the Each loop

$.each(list, function (i, item) {

});

Update #1

Update #2

Update #3

var l = list1.length; ...; l = list2.length;

The same applies to the for variables i, ii, iii.

Update #4

I notice a strange behavior in Chrome: the following pattern uses to repeat several times, going down for a while and then spikes up again.

During all this testes I close all the other chrome tabs and unnecessary applications. Trying to minimize unstable CPU availability.

Upvotes: 6

Views: 1134

Answers (1)

bikeshedder
bikeshedder

Reputation: 7487

Since you are benchmarking empty loops you give the JIT (just in time compiler) plenty of room for optimizations. It might be the case that the each call is removed all together as it has no side effects. The for loop however must run as the i is defined in the scope containing the for loop and not inside the for loop.

(function() {
    for (var i=0; i<10; i++) {}
    console.log(i); // outputs 10
})();

vs

(function() {
    [0,1,2,3,4,5,6,7,8,9].forEach(function(i) {});
    console.log(i); // i is not declared
})();

That is also the reasons why JSLint/JSHint complains about i being declared twice for the following code:

for (var i=0; i<10; i++) {}
for (var i=0; i<10; i++) {}

Upvotes: 1

Related Questions