Created
May 3, 2011 03:11
-
-
Save josephg/952760 to your computer and use it in GitHub Desktop.
Benchmarks of various JS reverse loop implementations
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
var arr = [] | |
for (var i = 0; i < 100000; i++) { | |
arr.push(i+1); | |
} | |
// This is what the coffeescript compiler produces for 'sum += arr[x] for x in [arr.nexts.length - 1..0]' | |
var coffee = function() { | |
var x, _ref, sum = 0; | |
for (x = _ref = arr.length - 1; _ref <= 0 ? x <= 0 : x >= 0; _ref <= 0 ? x++ : x--) { | |
sum += arr[x]; | |
} | |
return sum; | |
} | |
var js = function() { | |
var sum = 0; | |
for (var x = arr.length - 1; x >= 0; x--) { | |
sum += arr[x]; | |
} | |
return sum; | |
} | |
var sam = function() { | |
var sum = 0; | |
var x = arr.length; | |
while (x--) { | |
sum += arr[x]; | |
} | |
return sum; | |
} | |
var time = function(f) { | |
var start = Date.now(); | |
for (var i = 0; i < 100; i++) { | |
f(); | |
} | |
var end = Date.now(); | |
return end - start; | |
} | |
console.log("coffee: " + time(coffee)); | |
console.log("js: " + time(js)); | |
console.log("sam: " + time(sam)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment