Remove array elements with splice vs creating a new array

JavaScript performance comparison

Revision 3 of this test case created by

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var arr = [];
  for (var i = 0; i < 1000; i++) {
    arr.push(i);
  }
  
  function randomIndex() {
    return parseInt(Math.random() * arr.length);
  }
  
  function randomElement() {
    return arr[randomIndex()];
  }

};

Benchmark.prototype.teardown = function() {
  arr.length = 0;

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Splice
while (arr.length) {
  arr.splice(randomIndex(), 1);
}
pending…
New with Concat
while (arr.length) {
  var idx = randomIndex();
  arr = arr.slice(0, idx).concat(arr.slice(idx + 1));
}
pending…
New with iterative copy
while (arr.length) {
  var idx = randomIndex(),
      copy = [];
  
  for (var i in arr) {
     if (idx != i)
       copy.push(arr[i]);
  }

  arr = copy;
}
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.

0 Comments