1

I am looking to improve a function I wrote for array reversal. I was interested in writing my own just for practice and I came up with this:

function rArray(array){
    var temp = [];
    var len = array.length - 1;
        for(i = len, index = 0 ; i >= 0; i--, index++){
            temp.push(array[i]); // temp[index] = array[i];
        }
    return temp;
}

I am looking to 1.) improve speed, and two, create a more efficient function by leaving less of a footprint, I want to make a destructive reversing function. Can this be done with a for loop or must I use a while()? Thanks for the input.

user3412869
  • 1,395
  • 2
  • 10
  • 11

1 Answers1

3

You could get rid of index, since you aren't using it.

Or you could pre-allocate temp

     var temp = new Array(len);

You can't do both, though, since you would need index to add to the pre-allocated temp. You could run some experiments to see at what length pre-allocation becomes preferable (my guess: several million).

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144