JS Array Rotate

JavaScript performance comparison

Revision 8 of this test case created

Preparation code

<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

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
rotate
rotate(x, 0, x.length, Math.floor(Math.random() * x.length))
pending…
rotateArray
rotateArray(x, -Math.floor(Math.random() * x.length))
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