Adding items to array

JavaScript performance comparison

Revision 6 of this test case created by Kyle Simpson and last updated

Info

Various of ways to add items to an array

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Native push
var a = [];
for (var i = 0; i < 2000; i++) {
 a.push(i);
};
pending…
Native unshift
var a = [];
for (var i = 0; i < 2000; i++) {
 a.unshift(i);
};
pending…
length
var a = [];
for (var i = 0; i < 2000; i++) {
 a[a.length] = i;
};
pending…
Cached length
var a = [];
for (var length = 0; length < 2000; length++) {
 a[length] = length;
};
pending…
Concat
var a = [];
for (var i = 0; i < 2000; i++) {
 a.concat([i]);
};
pending…
alternate unshift
var a = [];
for (var i = 0; i < 2000; i++) {
 a = [i].concat(a)
};
pending…
Seeded push 1
var a = new Array(2000);
for (var i = 0; i < 2000; i++) {
 a.push(i);
};
pending…
Seeded push 2
var a = [];
a.length = 2000;
for (var i = 0; i < 2000; i++) {
 a.push(i);
};
pending…
Seeded unshift 1
var a = new Array(2000);
for (var i = 0; i < 2000; i++) {
 a.unshift(i);
};
pending…
Seeded unshift 1
var a = [];
a.length = 2000;
for (var i = 0; i < 2000; i++) {
 a.unshift(i);
};
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

Sam Foster commented :

The a[a.length] = i results are counter-intuitive. You’d think accessing length in each iteration would be slower. I could’ve sworn I’ve done this test before and got the opposite result, with push(i) being the fastest. Very interesting.

Jonas Fischer commented :

I think that a[a.length] = can be faster in some cases because it do not lookup the push function.

Add a comment