JS: Array.reverse() vs. for and while loops

JavaScript performance comparison

Revision 66 of this test case created by

Preparation code

<script>
    var array = [];
    for (var i = 0; i < 10000; i++) {
       array.push(i)
    }
    var length = array.length;
</script>
    

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Array.reverse()
array.reverse();
pending…
while push then slice
var left = 0;
while (left < length)
{
    array.push(array[length - 1 - ++left]);
    array.splice(length - 1 - left, 1);
}
pending…
while forward
var left = 0;
while (left < length)
{
    var right = length - 1 - left;
    array.push(array[right]);
    array.splice(right, 1);
    left += 1;
}
pending…
for push then slice
for (length -= 2; length > -1; length -= 1)
{
    array.push(array[length]);
    array.splice(length, 1);
}
pending…
for push
var result = [];
var i = null;
for (i = length - 1; i >= 0; i -= 1)
{
    result.push(array[i]);
}
pending…
for swap
var left = null;
var right = null;
for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
{
    var temporary = array[left];
    array[left] = array[right];
    array[right] = temporary;
}
pending…
for swap half
var left = null;
var right = null;
for (left = 0; left < length / 2; left += 1)
{
    right = length - 1 - left;
    var temporary = array[left];
    array[left] = array[right];
    array[right] = temporary;
}
pending…
XOR swap
var i = null;
var r = null;
for (i = 0, r = length - 1; i < r; i += 1, r -= 1)
{
    var left = array[i];
    var right = array[r];
    left ^= right;
    right ^= left;
    left ^= right;
    array[i] = left;
    array[r] = right;
}
pending…
XOR swap half
var i = null;
var r = null;
for (i = 0; i < length / 2; i += 1)
{
    r = length - 1 - i;
    var left = array[i];
    var right = array[r];
    left ^= right;
    right ^= left;
    left ^= right;
    array[i] = left;
    array[r] = right;
}
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.

0 Comments