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');
simple push:59ms
set length and push:192ms
new Array push:187ms
simple push:76ms
set length and push:44ms
new Array push:40ms
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?
I updated Chrome and FF results.
The push() method adds one or more elements to the end of an array and returns the new length of the 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.
JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array.
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.
Why is the new Array(N) the slowest?
console.log(arr0.length);
console.log(arr1.length);
console.log(arr2.length);
1000000
1000000
2000000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With