From the principle we can know that the efficiency of unshift is lower. The reason is that every element it adds, it moves the existing element down one position. But how effective is the difference? Let's test it here.
The main hardware of the test environment: CPU T7100 (1.8G), memory 4G DDR2 667, HDD 5400 RPM. Main software: Operating system for Windows 7, browser for Firefox 3.6.9. Test code:
var arr = [], s = +new Date; // push performance test for (var i = 0; i < 50000; I++) {Arr.push (i); } console.log ( +new Date- s); s = +new Date; arr = [ ]; // unshift performance test for (var i = 0; i < 50000; I++) {Arr.unsh IFT (i); } console.log ( +new date-s);
This code performs 50,000 push and unshift operations, one after another, to produce the result:
12
1152
As you can see, unshift is almost 100 times times slower than push! Therefore, usually should be cautious to use unshift, especially for large arrays. If we must achieve the unshift effect, is there any other way? The answer is yes.
The array has a method called reverse that can invert an array. First, the element to be put into the array is added with push, and then once reverse is executed, the unshift effect is achieved. Like what:
for (var i = 0; i < 50000; i++
The performance of reverse, and then to test:
var arr = [], s = +new for (var i = 0; i < 50000; i++) {Arr.push (i) ; } arr.reverse (); Console.log (+new
The result is:
12
Visible, reverse performance is very high, even without additional consumption, can be assured to use.
Array Push vs. Unshift method Performance Comparison analysis