Forward Loop Vs Bakward Loop (javascript)

JavaScript performance comparison

Test case created by Hammad Tariq

Info

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 code

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

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

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

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment