Length equal 0 or new array

JavaScript performance comparison

Revision 6 of this test case created


It should test what is more efficient way to clear an array.

Creating NEW with:

a = [];

or make the length equal 0 like this :

a.length = 0;

NOTE : Those two methods are not equal in their behaviour! First one (a = []) will make all NEW array, and second one (a.length = 0) modify current one! I is very important if you HAVE other references to that array!

Preparation code

Benchmark.prototype.setup = function() {
    a = [1, 2, 3, 4, 5, 6, 7, 7];

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
New array method
a = [];
length equal to 0 method
a.length = 0;
Defining length isn't like usual "resetting" value
a.randomProperty = 0 // see the performance difference with setting length
while (a.length > 0) a.pop();
while 2
while (a.pop());

Compare results of other browsers


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:


Mientjan commented :

var a = []; is not the right way to empty a array.

Arrays are objects and have pointers. So var a = []; should be removed.

Mientjan commented :

a.randomProperty = 0 is not resetting the length of the array / removing its items. should be removed from this perf.

Comment form temporarily disabled.

Add a comment