Union

JavaScript performance comparison

Revision 2 of this test case created by Cezary Tomczyk

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var listone = [],
    listtwo = [];
  
  for (var i = 0; i < 1000; i++) {
    listone.push(i);
    listtwo.push(i * 2);
  }
  
  function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
  }
  
  function extend(destination, source) {
              var key;
              for (key in source) {
                  if (Object.prototype.hasOwnProperty.call(source, key)) {
                          destination[key] = source[key];
                  }
              }
              return destination;
          };
  
  function union(o,p) { return extend(extend({},o), p); }
  
  

};
</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
Iterate both lists
var union = listone.slice(0);
for (var i = 0, len = listtwo.length; i < len; i++) {
  var contains = false;

  for (var j = 0, len2 = union.length; j < len2; j++) {
    if (listtwo[i] == union[j]) {
      contains = true;
      break;
    }
  }

  if (!contains) union.push(listtwo[i]);
}
pending…
Dictionary lookup
var union = listone.slice(0);
var dict = {};
for (var i = 0, len = union.length; i < len; i++) {
  dict[union[i]] = null;
}

for (var i = 0, len = listtwo.length; i < len; i++) {
  if (!dict.hasOwnProperty(listtwo[i])) {
    dict[listtwo[i]] = null;
    union.push(listtwo[i]);
  }
}
pending…
concat + filter
listone.concat(listtwo).filter(onlyUnique);
pending…
union extend
union(listone, listtwo);
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