Skip to content

Instantly share code, notes, and snippets.

@slosd
Created February 9, 2012 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slosd/1780215 to your computer and use it in GitHub Desktop.
Save slosd/1780215 to your computer and use it in GitHub Desktop.
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