JS: Array.reverse() vs while loop

JavaScript performance comparison

Test case created by Matt McDonald

Info

Checking performance of Array.reverse() vs a quick while loop.

Preparation code

<script>
  var ar = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  var len = ar.length;
  var backwardI = len - 1;
  var forwardI = 0;
</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
Array.reverse()
ar.reverse();
pending…
Backward while loop
while (backwardI > -1) {
 ar.push(ar[backwardI]);
 ar.splice(backwardI, 1);
 backwardI--;
}
pending…
Forward while loop
while (forwardI < len) {
 var end = (len - 1) - forwardI;
 ar.push(ar[end]);
 ar.splice(end, 1);
 forwardI++;
}
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