concat vs merge vs push

JavaScript performance comparison

Revision 2 of this test case created by Xav

Info

Take an object array add a new member to each entry.

Comparison * concat -> update + map * merge -> update + map * each -> update + push * each -> push + update * for loop -> update + push

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//raw.github.com/documentcloud/underscore/master/underscore.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var baseArray = [
      {name: "foo"},
      {name: "bar"},
      {name: "baz"}
    ];
   
    //modified arrays
    var catArray = merArray = pushArray = [];
   
    // Caches
    var x, _i, _len;
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Concat
catArray = catArray.concat($.map(baseArray, function(value)
   {
      value["bla"] = "Banana";
      return value;
   })
);
pending…
Merge
$.merge(merArray, $.map(baseArray, function(value)
   {
      value["bla"] = "Banana";
      return value;
   })
);
pending…
Update then push
_.each(baseArray, function(val)
   {
     val['bla'] = 'Banana';
     pushArray.push(val);
   }
)
pending…
Push, then update
_.each(baseArray, function(val)
   {
     pushArray[pushArray.push(val) - 1]['bla'] = 'Banana';
   }
)
pending…
For loop, update then push
for (_i = 0, _len = baseArray.length; _i < _len; _i++) {
  x = baseArray[_i];
  x.bla = 'Banana';
  pushArray.push(x);
}
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