Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a javascript array work whilst pushing new elements?

I tested this code in Chrome / Firefox :

console.time('simple push');
var arr0 = [];
for(var i =0; i < 1000000; i++){
    arr0.push(i);
}
console.timeEnd('simple push');
console.time('set length and push');
var arr1 = [];
arr1.length=1000000;
for(var j =0; j < 1000000; j++){
    arr1[j]=j;
}
console.timeEnd('set length and push');
console.time('new Array push');
var arr2 = new Array(1000000);
for(var k =0; k < 1000000; k++){
    arr2[k]=k;
}
console.timeEnd('new Array push');

Chrome 13 Result

simple push:59ms
set length and push:192ms
new Array push:187ms

Firefox 4 Result

simple push:76ms
set length and push:44ms
new Array push:40ms

My doubt

So new Array operation is definitely the slowest, but I wanna know why?
Why set length behaves different in Chrome and Firefox, it seems preallocated memory doesn't works well in Chrome?

Update

I updated Chrome and FF results.

like image 607
simon xu Avatar asked Aug 22 '11 17:08

simon xu


People also ask

How does array Push work in JavaScript?

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Does push modify an array?

Examples of push in JavaScript and common errors Reassigning the array with the output from push is a common error. To avoid this error you need to remember that push changes the array, and returns the new length. If you reassign the variable with the return value from push() you are overwriting the array value.

Does Push create a new array JavaScript?

JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array.

Can you push objects into an array JavaScript?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.


1 Answers

Why is the new Array(N) the slowest?

console.log(arr0.length);
console.log(arr1.length);
console.log(arr2.length);

1000000
1000000
2000000
like image 186
Jimmy Avatar answered Oct 08 '22 00:10

Jimmy