It can be known from the principle that the efficiency of the unshift is lower. The reason is that it moves the existing element down one place, each adding an element. But how much efficiency difference is there? Let's test it here.
Primary hardware for the test environment: CPU T7100 (1.8G), memory 4G DDR2 667, hard drive 5400 rpm. Main software: Operating system for Windows 7; browser for Firefox 3.6.9. Test code:
Copy Code code as follows:
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.unshift (i);
}
Console.log (+new date-s);
This code performs 50,000 push and unshift operations, and after running once, results:
12
1152
Visible, Unshift is about 100 times times slower than push! Therefore, usually still should be cautious with unshift, especially for large arrays. If you must achieve the effect of unshift, is there any other way? The answer is yes.
Array has a method called reverse that can invert an array. First, the elements to be put into the array with the push to add, and then perform a reverse, it reached the unshift effect. Like what:
Copy Code code as follows:
for (var i = 0; i < 50000; i++) {
Arr.push (i);
}
Arr.reverse ();
What about the performance of the reverse, and then test the following:
Copy Code code as follows:
var arr = [], s = +new Date;
for (var i = 0; i < 50000; i++) {
Arr.push (i);
}
Arr.reverse ();
Console.log (+new date-s);
The result:
12
Visible, reverse performance is very high, and even no additional consumption, you can rest assured that use.