Performance comparison and analysis of the push and Unshift methods of array _javascript skills

Source: Internet
Author: User
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.

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.