JS Array Rotate (v10)

Revision 10 of this benchmark created by 4esn0k on


Preparation HTML

<script>

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

function rotate0(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);
    }
  }
}

function rotate1(a, from, to, k) {
  var n = to - from;
  k = (k % n + n) % n;
  var c = n;
  while (c > 0) {
    var previous = from;
    var saved = a[from];
    var i = previous + k;
    while (i !== from) {
      a[previous] = a[i];
      --c;
      previous = i;
      i += k;
      if (i >= to) {
        i -= n;
      }
    }
    a[previous] = saved;
    --c;
    ++from;
  }
};

function rotate2(a, from, to, k) {
  var n = to - from;
  if (n > 0) {
    k = -k;
    k = (k % n + n) % n;
    while (k !== 0) {
      var i = n + from;
      while (--i >= k + from) {
        var x = a[i];
        a[i] = a[i - k];
        a[i - k] = x;
      }
      var p = n % k;
      n = k;
      k -= p;
      if (p === 0) {
        k = 0;
      }
    }
  }
};


var x = [];
var size = 1e5;
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
rotate0
rotate0(x, 0, x.length, Math.floor(Math.random() * x.length))
ready
rotate1
rotate1(x, 0, x.length, Math.floor(Math.random() * x.length))
ready
rotate2
rotate2(x, 0, x.length, 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.