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

JavaScript performance comparison

Revision 9 of this test case created by Boris

Info

Checking performance of Array.reverse() vs custom loops.

See http://stackoverflow.com/questions/5276953/what-is-the-most-efficient-way-to-reverse-an-array-in-javascript.

Also see http://jsperf.com/forloop-vs-reverse-while-loop-and-array-reverse/9.

Preparation code

<script>
    var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    var length = array.length;
</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()
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
var len = length;
for (len -= 2; len > -1; len -= 1)
{
    array.push(array[len]);
    array.splice(len, 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…
destructuring
var left = null;
var right = null;
for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
{
    [array[left], array[right]] = [array[right], array[left]];
}
pending…
destructuring half
var left = null;
var right = null;
for (left = 0; left < length / 2; left += 1)
{
    right = length - 1 - left;
    [array[left], array[right]] = [array[right], array[left]];
}
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