for loop craziness

by khrome

HTML

<h1>
  Check the console
</h1>

JavaScript

var arr = [];
for (var i = 0; i < 100000; i++) arr[i] = i;

var numberOfRuns = 100;

function runTest(name, f) {
    var totalTime = 0;
    console.time(name);

    for (var r = 0; r < numberOfRuns; r++) {
        f();
    }

    return console.timeEnd(name);
}

function testFunction(v) {
    v;
}

var forTime = runTest('for', function() {
    for (var j = 0; j < arr.length; j++) {
        testFunction(arr[j]);
    }
});

var forEachTime = runTest('forEach', function() {
    arr.forEach(testFunction);
});

Array.prototype.forWithoutScope = function(testFunction) {
    var len = this.length;
    for (var j = 0; j < len; j++) {
        testFunction(this[j], j);
    }
};

var forWithoutScopeTime = runTest('forWithoutScope', function() {
    arr.forWithoutScope(testFunction);
});

Array.prototype.forWithScope = function(testFunction) {
    for (var j = 0; j < this.length; j++) {
        testFunction.apply(this, [this[j], j]);
    }
};

var forWithScopeTime = runTest('forWithScope', function() {
    arr.forWithScope(testFunction);
});


var underEachTime = runTest('underEach', function() {
    _.each(arr, testFunction);
});