JS Array Rotate (v8)

Revision 8 of this benchmark created on


Preparation HTML

<script>
var rotateArray = function(a, inc) {
    for (var l = a.length, inc = (Math.abs(inc) >= l && (inc %= l), inc < 0 && (inc += l), inc), i, x; inc; inc = (Math.ceil(l / inc) - 1) * inc - l + (l = inc))
    for (i = l; i > inc; x = a[--i], a[i] = a[i - inc], a[i - inc] = x);
    return a;
};

function reverse(a, from, to) {
  --from;
  while (++from < --to) {
    var tmp = a[from];
    a[from] = a[to];
    a[to] = tmp;
  }
}

function rotate(a, from, to, k) {
  var n = to - from;
  if (n > 0) {
    k = (k % n + n) % n;
    if (k > 0) {
      reverse(a, from, from + k);
      reverse(a, from + k, to);
      reverse(a, from, to);
    }
  }
}



var x = [];
var size = 1e3;
var i = -1;
while (++i < size) {
  x.push(Math.floor(Math.random() * Math.pow(2, 30)));
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
rotate
rotate(x, 0, x.length, Math.floor(Math.random() * x.length))
ready
rotateArray
rotateArray(x, -Math.floor(Math.random() * x.length))
ready

Revisions

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