I was asked recently what was the most efficient way to reverse an array in JavaScript. At the moment, I suggested using a for loop and fiddling with the array but then realized there is a native Array.reverse() method.
For curiosity’s sake, can anyone help me explore this by showing examples or pointing in the right direction so I can read into this? Any suggestions regarding how to measure performance would be awesome too.
Based on this setup:
Array.reverse();is the first or second slowest!The benchmarks are here:
https://jsperf.com/js-array-reverse-vs-while-loop/9
Across browsers, swap loops are faster. There are two common types of swap algorithms (see Wikipedia), each with two variations.
The two types of swap algorithms are temporary swap and XOR swap.
The two variations handle index calculations differently. The first variation compares the current left index and the right index and then decrements the right index of the array. The second variation compares the current left index and the length divided by half and then recalculates the right index for each iteration.
You may or may not see huge differences between the two variations. For example, in Chrome 18, the first variations of the temporary swap and XOR swap are over 60% slower than the second variations, but in Opera 12, both variations of the temporary swap and XOR swap have similar performance.
Temporary swap:
First variation:
Second variation:
XOR swap:
First variation:
Second variation:
There is another swap method called destructuring assignment:
http://wiki.ecmascript.org/doku.php?id=harmony:destructuring
Destructuring assignment:
First variation:
Second variation:
Right now, an algorithm using destructuring assignment is the slowest of them all. It is even slower than
Array.reverse();. However, the algorithms using destructuring assignments andArray.reverse();methods are the shortest examples, and they look the cleanest. I hope their performance gets better in the future.Another mention is that modern browsers are improving their performance of array
pushandspliceoperations.In Firefox 10, this
forloop algorithm using arraypushandsplicerivals the temporary swap and XOR swap loop algorithms.However, you should probably stick with the swap loop algorithms until many of the other browsers match or exceed their array
pushandspliceperformance.