Forward Loop Vs Bakward Loop (javascript)

Benchmark created by Hammad Tariq on


Description

Just if you want to test the popular claim that looping backward in an array is faster than looping forward. Added a reverse while loop test as well, Looping backward is faster than forward loop and while reverse is better than all of the above.

Preparation HTML

<script>
  var arr = ["a", "b", "c", "d"];
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
forward loop
for (i = 0; i < arr.length; i++) {
 alert(arr[i]);
}
ready
backward loop
for (i = arr.length - 1; i >= 0; i--) {
 alert(arr[i]);
}
ready
backward while loop
var i = arr.length;
while (--i >= 0) {
 alert(arr[i]);
}
ready
foreach loop
for (var i in arr) {
 alert(arr[i]);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.