public
Last active

performance test of some for loop variations

  • Download Gist
for-loops.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<!doctype html>
<html>
<head>
<title>For loop tests</title>
<script src="for-loops.js"></script>
</head>
<body>
<script>
test_forClassic();
test_forLength();
test_forShort();
</script>
</body>
</html>
for-loops.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
/* Timer helper functions */
var start;
var end;
 
function startTimer() {
start = new Date();
}
 
function endTimer() {
end = new Date();
}
 
function getMilliseconds() {
return end.getTime() - start.getTime();
}
 
/* Test parameters */
var elements = 1000000;
 
/* Test data helper functions */
function getTestData() {
var a = [];
for (var i = elements; i >= 0; i--) {
a[i] = i + 1;
}
return a;
}
 
/* Test cases */
function Process(data) {
return data * data;
}
 
function test_forClassic() {
var a = getTestData();
startTimer();
for (var i = 0; i < a.length; i++) {
Process(a[i]);
}
endTimer();
console.log("Classic for loop: " + getMilliseconds() + "ms");
}
 
function test_forLength() {
var a = getTestData();
startTimer();
for (var i = 0, len = a.length; i < len; i++) {
Process(a[i]);
}
endTimer();
console.log("For loop with length cached: " + getMilliseconds() + "ms");
}
 
function test_forShort() {
var a = getTestData();
startTimer();
for (var i = 0, item; item = a[i++];) {
Process(item);
}
endTimer();
console.log("For loop with short signature: " + getMilliseconds() + "ms");
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.