JS: Array.reverse() vs while loop (v4)

Revision 4 of this benchmark created by george on


Description

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

Preparation HTML

<script>
  var ar = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  var backwardI = len - 1;
  var forwardI = 0;
  var len = ar.length;
  
  var reverse = function(arr) {
   var result = [],
       ii = arr.length;
   for (var i = ii - 1; i !== 0; i--) {
    result.push(arr[i]);
   }
   return result;
  }
  
  Array.prototype.inlinereverse = function() {
   var len = this.length,
       forwardI = 0;
   while (forwardI < len) {
    var end = (len - 1) - forwardI;
    this.push(this[end]);
    this.splice(end, 1);
    forwardI++;
   }
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Array.reverse()
ar.reverse();
ready
push then slice
while(forwardI<len)
{
  ar.push(ar[len-1-++forwardI]);
  ar.splice(len-1-forwardI,1);
}
ready
Forward while loop
while (forwardI < len) {
 var end = (len - 1) - forwardI;
 ar.push(ar[end]);
 ar.splice(end, 1);
 forwardI++;
}
ready
for(len=len-2;len>-1;len--) {
 ar.push(ar[len]);
 ar.splice(len, 1);
}
ready

Revisions

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