Performance comparison analysis of the push and Unshift methods of array

Source: Internet
Author: User

From the principle we can know that the efficiency of unshift is lower. The reason is that every element it adds, it moves the existing element down one position. But how effective is the difference? Let's test it here.
The main hardware of the test environment: CPU T7100 (1.8G), memory 4G DDR2 667, HDD 5400 RPM. Main software: Operating system for Windows 7, browser for 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.unsh IFT (i); } console.log ( +new  date-s); 

This code performs 50,000 push and unshift operations, one after another, to produce the result:
12
1152
As you can see, unshift is almost 100 times times slower than push! Therefore, usually should be cautious to use unshift, especially for large arrays. If we must achieve the unshift effect, is there any other way? The answer is yes.
The array has a method called reverse that can invert an array. First, the element to be put into the array is added with push, and then once reverse is executed, the unshift effect is achieved. Like what:

 for (var i = 0; i < 50000; i++

The performance of reverse, and then to test:
var arr = [], s = +new for (var i = 0; i < 50000; i++) {Arr.push (i) ; } arr.reverse (); Console.log (+new

The result is:
12
Visible, reverse performance is very high, even without additional consumption, can be assured to use.

Array Push vs. Unshift method Performance Comparison analysis

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.