Splice vs Push

JavaScript performance comparison

Test case created by Drew Wells

Info

There is no easy way to replace the entire contents of an array in JavaScript. This compares the performance of splice to push.

Preparation code

<script>
  var a = [];
  a.length = 10000;
  var b = [];
  b.length = 10000;
  var c = [];
  c.length = 10000;
  var d = [];
  d.length = 10000;
  var aps = Array.prototype.splice;
</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
//Replace a with c
c.unshift(a.length);
c.unshift(0);
aps.apply(a, c);
pending…
Push
//Replace b with d
b.length = 0;
for (var i = 0, l = d.length; i < l; i++) {
 b.push(d[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:

1 comment

John-David Dalton commented :

The big difference is you're modifying c directly and not doing the same for d. I created revision 2 to avoid modifying the source arrays directly.

Add a comment