Created
February 9, 2012 14:12
-
-
Save slosd/1780215 to your computer and use it in GitHub Desktop.
performance test of some for loop variations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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