Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
performance test of some for loop variations
<!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>
/* 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");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.