Remove array elements with splice vs creating a new array

JavaScript performance comparison

Revision 5 of this test case created

Info

This is purely a speed test, obviously creating new arrays every time will increase memory usage and force the GC to run more often

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 unknown unknown
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(),
      count = arr.length,
      i = 0,
      copy = [];
 
  for (; i < idx; i++) {
      copy.push(arr[i]);
  }
  i++;
  for (; i < count; i++) {
      copy.push(arr[i]);
  }

  arr = copy;
}
pending…
Splice with concat
while (arr.length) {
  arr.splice(randomIndex(), 1);
  arr = arr.concat([]);
}
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:

0 comments

Add a comment