Comparison and Analysis of the push and unshift methods of Array

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.