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.

2

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.