forloop vs reverse while loop and array reverse

JavaScript performance comparison

Revision 10 of this test case created by XP1

Info

I know that reverse while looping in javascript is faster than for looping, but if order is to be maintained, would rev-while looping then reversing the array be faster or would the traditional for loop out perform this combo?

See http://jsperf.com/js-array-reverse-vs-while-loop/5.

See http://jsperf.com/array-push-reverse-vs-unshift-reverse for array push reverse vs. unshift reverse.

See http://jsperf.com/array-push-vs-unshift/6 for array push vs. unshift reversal.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    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
for
var start = null;
var end = null;
for (start = 0; start < length / 2; start += 1) {
  var temporary = array[start];
  end = length - 1 - start;
  array[start] = array[end];
  array[end] = temporary;
}
pending…
for reverse
var end = null;
var start = null;
for (end = length - 1; end >= length / 2; end -= 1) {
  var temporary = array[end];
  start = length - 1 - end;
  array[end] = array[start];
  array[start] = temporary;
}
pending…
while
var start = 0;
var end = null;
while (start < length / 2) {
  var temporary = array[start];
  end = length - 1 - start;
  array[start] = array[end];
  array[end] = temporary;
  start += 1;
}
pending…
while reverse
var end = length - 1;
var start = null;
while (end >= length / 2) {
  var temporary = array[end];
  start = length - 1 - end;
  array[end] = array[start];
  array[start] = temporary;
  end -= 1;
}
pending…
reverse
array.reverse();
pending…
push
var temporary = [];
var i = null;
for (i = 0; i < length; i += 1) {
  temporary.push(array[i]);
}
array = temporary;
pending…
unshift
var temporary = [];
var i = null;
for (i = 0; i < length; i += 1) {
  temporary.unshift(array[i]);
}
array = temporary;
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