Empty JavaScript array (v15)

Revision 15 of this benchmark created on


Description

Original discussion at http://stackoverflow.com/questions/1232040/how-to-empty-an-array-in-javascript.

Setup

function makeid() {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
      for (var i = 0; i < 15; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    
      return text;
    }
    
    var small = [],
      medium = [],
      big = [],
      bigObject = [],
      smallSize = 100,
      mediumSize = 10000,
      bigSize = 100000,
      bigObjectSize = 100000,
      empty = [];
    
    while (smallSize--) {
      small.push(Math.random());
    }
    
    while (mediumSize--) {
      medium.push(Math.random());
    }
    
    while (bigSize--) {
      big.push(Math.random());
    }
    
    while (bigObjectSize--) {
      bigObject.push({
        id: Math.random(),
        name: makeid()
      })
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Overwriting with a new array (small)
small = [];
ready
Overwriting with a new array (medium)
medium = [];
ready
Overwriting with a new array (big)
big = [];
ready
Setting length to 0 (small)
small.length = 0;
ready
Setting length to 0 (medium)
medium.length = 0;
ready
Setting length to 0 (big)
big.length = 0;
ready
Using splice (small)
small.splice(0, small.length);
ready
Using splice (medium)
medium.splice(0, medium.length);
ready
Using splice (big)
big.splice(0, big.length);
ready
Using while, pop (small)
while (small.length > 0) {
  small.pop();
}
ready
Using while, pop (medium)
while (medium.length > 0) {
  medium.pop();
}
ready
Using while, pop (big)
while (big.length > 0) {
  big.pop();
}
ready
for loop big
for (var i = big.length; i; i--) big.pop();
ready
Overwriting with a new array (bigObject)
bigObject = [];
ready
Setting length to 0 (bigObject)
bigObject.length = 0;
ready
Using splice (bigObject)
bigObject.splice(0, bigObject.length);
ready
Using while, pop (bigObject)
while (bigObject.length > 0) {
  bigObject.pop();
}
ready
for loop bigObject
for (var i = bigObject.length; i; i--) bigObject.pop();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.