foreach vs for loop

Benchmark created by Jason on


Description

testing script#'s foreach vs a standard for loop

Setup

var testArray = [4, 5, 6, 7, 8, 9, 10];
    var ArrayEnumerator = function ArrayEnumerator$(array) {
      this._array = array;
      this._index = -1;
      this.current = null;
    }
    
    ArrayEnumerator.prototype = {
      moveNext: function ArrayEnumerator$moveNext() {
        this._index++;
        this.current = this._array[this._index];
        return (this._index < this._array.length);
      },
      reset: function ArrayEnumerator$reset() {
        this._index = -1;
        this.current = null;
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
for-loop
var count = testArray.length;
var sum = 0;
for (var i = 0; i < count; i++) {
  sum += testArray[i];
}
ready
foreach-loop
var $enum1 = new ArrayEnumerator(testArray);
var sum = 0;
while ($enum1.moveNext()) {
  sum += $enum1.current;
}
ready

Revisions

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