JavaScript best practices – time your functions while developing

by riddla

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css">
<div class="alert alert-info">
     <h2>See the Chrome console for results</h2>
</div>

JavaScript

var wrapWithTimer = function (label, f) {
    console.time(label);
    f();
    console.timeEnd(label);
};

// see http://jsperf.com/loops/91
var arr = new Array(100);
for (var j = 0, n = arr.length; j < n; j++) {
    arr[j] = Math.random();
}

wrapWithTimer('RoadRunnerIsSlow', function () {
    var z = 0;
    arr.forEach(function (x) {
        z += x;
    });
});

wrapWithTimer('RoadRunnerIsFaster', function () {
    var z = 0;
    for (var i = 0, len = arr.length; i < len; ++i) {
        z += arr[i];
    }
});