From the principle, we can know that the unshift efficiency is low. The reason is that every time an element is added, the existing element must be moved down to a position. But what is the difference in efficiency? Let's test it.
Main hardware in the test environment: CPU T7100 (1.8 GB), memory 4 GB DDR2 667, hard disk 5400 rpm. Main software: Windows 7 and Firefox 3.6.9. Test code:
Copy codeThe Code is 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 executes 50000 push and unshift Operations respectively. After one operation, the result is obtained:
12
1152
Obviously, unshift is about 100 times slower than push! Therefore, you should always use unshift with caution, especially for large arrays. Is there any other way to achieve the unshift effect? The answer is yes.
Array has a method called reverse that can reverse an Array. First, add the elements to be put in the array with push, and then execute reverse to achieve the unshift effect. For example:Copy codeThe Code is as follows: for (var I = 0; I <50000; I ++ ){
Arr. push (I );
}
Arr. reverse ();
What about the performance of reverse? Let's test it again:Copy codeThe Code is 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 is:
12
It can be seen that the reverse performance is extremely high, and there is no additional consumption, you can use it with confidence.