find array singles
JavaScript performance comparison
Info
Stackoverflow - http://stackoverflow.com/q/8699357/918414
Preparation code
<script>
Benchmark.prototype.setup = function() {
var items1 = ['txfa2', 'txfa9', 'txfa2', 'txfa1', 'txfa3', 'txfa4', 'txfa8', 'txfa9', 'txfa2', 'txfa8'];
var items2 = ['txfa2', 'txfa9', 'txfa2', 'txfa1', 'txfa3', 'txfa4', 'txfa8', 'txfa9', 'txfa2', 'txfa8', 'txfa9', 'txfa2', 'txfa1', 'txfa3', 'txfa4'];
var items3 = ['txfa2', 'txfa2', 'txfa2', 'txfa2', 'txfa2', 'txfa2', 'txfa2', 'txfa2', 'txfa2', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa7'];
var items4 = ['txfa2', 'txfa2', 'txfa2', 'txfa3', 'txfa4', 'txfa2', 'txfa2', 'txfa2', 'txfa4', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa2', 'txfa2', 'txfa4', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa2', 'txfa2', 'txfa4', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa2', 'txfa2', 'txfa4', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa2', 'txfa2', 'txfa4', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa2', 'txfa2', 'txfa4', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa2', 'txfa2', 'txfa4', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa2', 'txfa2', 'txfa4', 'txfa9', 'txfa7', 'txfa7', 'txfa7', 'txfa7', 'txfa7'];
function singlesIndexOf( array ) {
for( var index = 0, single = []; index < array.length; index++ ) {
if( array.indexOf( array[index], array.indexOf( array[index] ) + 1 ) == -1 ) single.push( array[index] );
};
return single;
};
function singlesJSObject( array ) {
var result = []
, i
, k
, container = {};
for (i = 0; i < array.length; ++i) {
if (array[i] in container) {
container[array[i]]++;
} else {
container[array[i]] = 1;
}
}
for (k in container) {
if (container[k] == 1) {
result.push(k);
}
}
return result;
};
function singlesReduce( array ) {
// create a map from value -> count(value)
var keys = array.reduce(function(o, k) {
o[k] = o[k] ? o[k] + 1 : 1;
return o;
}, {});
// find those that only appeared once
return Object.getOwnPropertyNames(keys).filter(function(k) {
return (keys[k] === 1);
});
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
singlesIndexOf |
|
pending… |
singlesJSObject |
|
pending… |
singlesReduce |
|
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:
- Revision 1: published by ThinkingStiff
- Revision 2: published
- Revision 3: published by ThinkingStiff and last updated
0 comments