


Comparative analysis of performance of Array's push and unshift methods_javascript skills
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Sort array using Array.Sort function in C#

Simple and clear method to use PHP array_merge_recursive() function

How to use the array_combine function in PHP to combine two arrays into an associative array

Detailed explanation of PHP array_fill() function usage

How to use the Array module in Python

What are the common causes of ArrayStoreException in Java?

Introduction to how to use the PHP array_change_key_case() function

Introduction to the usage of PHP array_flip() function
