Array#intersect

JavaScript performance comparison

Test case created by Vic

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7/prototype.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        a2 = [0, 2, 4, 8];
   
    Array.prototype.intersect2 = function intersect2(array) {
      return this.uniq().findAll(function(item) {
        return array.detect(function(value) {
          return item === value;
        }) >= 0;
      });
    };
   
    Array.prototype.intersect3 = function intersect3(array) {
      return this.uniq().filter(function(item) {
        return array.indexOf(item) !== -1;
      });
    };
   
    Array.prototype.intersect4 = function intersect4(array) {
      var r = [],
          b = this.concat([]).sort().uniq(true).concat(array.concat([]).sort().uniq(true)).sort(),
          x = b.length;
      if (x > 0) {
        for (; --x;) {
          if (b[x] === b[x - 1] && r[0] !== b[x]) {
            r.unshift(b[x]);
          }
        }
      }
      return r;
    };
   
    Array.prototype.intersect5 = function intersect5(array) {
      var r = [],
          x, b = this.concat([]).sort().uniq(true).concat(array.concat([]).sort().uniq(true)).sort(),
          i = b.length;
      if (i > 0) {
        for (; --i;) {
          if (b[i] === b[i - 1] && x !== b[i]) {
            x = b[i];
            r.unshift(x);
          }
        }
      }
      return r;
    };
};
</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
Array#intersect
a1.intersect(a2)
pending…
intersect-2-detect
a1.intersect2(a2)
pending…
intersect-3-indexOf
a1.intersect3(a2)
pending…
intersect-4-for
a1.intersect4(a2)
pending…
intersect-5-for
a1.intersect5(a2)
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment