Array#intersect
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
Array#intersect |
|
pending… |
intersect-2-detect |
|
pending… |
intersect-3-indexOf |
|
pending… |
intersect-4-for |
|
pending… |
intersect-5-for |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments