Compare loops (v3)

Revision 3 of this benchmark created by d4rkr00t on


Description

Compare different approaches for loops in javascript.

Setup

var list = Array(1000000).join(',').split(',').map(function() {
      return Math.floor(Math.random() * (1000000 - 1 + 1)) + 1;
    });

Test runner

Ready to run.

Testing in
TestOps/sec
Simple For Loop
var totalSum = 0;

for (var i = 0; i < list.length; i++) {
  totalSum += list[i] * list[i];
}
ready
For Loop With Max
var totalSum = 0;

for (var i = 0, max = list.length; i < max; i++) {
  totalSum += list[i] * list[i];
}
ready
Inverted For Loop
var totalSum = 0;

for (var i = list.length - 1; i >= 0; i--) {
  totalSum += list[i] * list[i];
};
ready
Simple While
var totalSum = 0,
  i = 0,
  max = list.length;
while (i < max) {
  totalSum += list[i] * list[i];
  i++;
}
ready
Reverse While
var totalSum = 0,
  i = list.length;

while (i--) {
  totalSum += list[i] * list[i];
}
ready
For In
var totalSum = 0;

for (i in list) {
  totalSum += i * i;
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.