From the principle, we can know that the efficiency of unshift is low. The reason is that every time it adds an element, it moves the existing element down one position. But how big is the efficiency difference? Let’s test it out below.
The main hardware of the test environment: CPU T7100 (1.8G); memory 4G DDR2 667; hard disk 5400 rpm. Main software: The operating system is Windows 7; the browser is 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.unshift(i);
}
console.log( new Date - s);
This code performs push and unshift operations 50,000 times respectively. After running once, The result is:
12
1152
It can be seen that unshift is almost 100 times slower than push! Therefore, you should still use unshift with caution, especially for large arrays. So if we must achieve the unshift effect, are there any other methods? The answer is yes.
Array has a method called reverse, which can reverse an array. First use push to add the elements to be put into the array, and then perform reverse again to achieve the unshift effect. For example:
for (var i = 0; i < 50000; i ) {
arr.push(i);
}
arr.reverse();
What about the performance of reverse? Let’s test it again:
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, so you can use it with confidence.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn