For loops in few different ways

JavaScript performance comparison

Test case created by tswistak

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js" integrity="sha256-7/yoZS3548fXSRXqc/xYzjsmuW3sFKzuvOCHd06Pmps=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
      
<script>
Benchmark.prototype.setup = function() {
  var array = [];
  for (var i = 0; i < 1000000; i++) {
      array.push(i);
  }

};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
ForEach
var sum = 0;
array.forEach(function(current) { sum += current; });
pending…
For...of
var sum = 0;
for (var current of array) {
    sum += current;
}
pending…
For...in
var sum = 0;
for (var current in array) {
    sum += current;
}
pending…
For
var sum = 0;
for (var i = 0; i < array.length; i++) {
    sum += array[i];
}
pending…
For with iterator
var sum = 0;
var iterator = array[Symbol.iterator]();
for (var current = iterator.next(); !current.done; current = iterator.next()) {
    sum += current.value;
}
pending…
Lodash forEach
var sum = 0;
_.forEach(array, function(current) { sum += current; });
pending…
jQuery each
var sum = 0;
$.each(array, function(current) { sum += current; });
pending…

Compare results of other browsers

Revisions

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

0 Comments