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

Revision 66 of this benchmark created on


Description

Preparation HTML

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

Test runner

Ready to run.

Testing in
TestOps/sec
Array.reverse()
array.reverse();
ready
while push then slice
var left = 0;
while (left < length)
{
    array.push(array[length - 1 - ++left]);
    array.splice(length - 1 - left, 1);
}
ready
while forward
var left = 0;
while (left < length)
{
    var right = length - 1 - left;
    array.push(array[right]);
    array.splice(right, 1);
    left += 1;
}
ready
for push then slice
for (length -= 2; length > -1; length -= 1)
{
    array.push(array[length]);
    array.splice(length, 1);
}
ready
for push
var result = [];
var i = null;
for (i = length - 1; i >= 0; i -= 1)
{
    result.push(array[i]);
}
ready
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;
}
ready
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;
}
ready
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;
}
ready
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;
}
ready

Revisions

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