jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
Just trying to find a performant way of creating a "uniqued" array that leave copies in, only removed actual duplicate entries (obj === obj).
Set does not work properly in IE/Safari so they will use the first algorithm.
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
window.N = 999;
var initialArray = [];
var seeds = [{ one: 1 }, { two: 2 }, { three: 3 }];
var setSupport = (function(){
var s = new Set([1,2]);
return s.size == 2;
})();
for(var i = 0, len = N; i < len; i++) {
var isCopy = i % 2;
var seed = seeds[(i % 3)];
if(isCopy) {
initialArray.push(_.clone(seed));
} else {
initialArray.push(seed);
}
}
var result;
function uniq1(ar) {
var copy = ar.slice(0, ar.length);
var result = [];
for (var i = 0, len = copy.length, item; i < len; i++) {
item = copy.shift();
if (copy.indexOf(item) === -1) {
result.push(item);
}
}
return result;
}
function uniq2(ar) {
var r = [];
var s = new Set(ar);
s.forEach(function(val) {
r.push(val);
});
return r;
}
if(!setSupport){
uniq2 = uniq1;
}
function uniq3(arr) {
var uniqArr = [],
expando = "__expando234234i028290348",
instance;
// check for expando and add it
for (var i = 0, len = arr.length; i < len; i++) {
instance = arr[i];
if (!instance[expando]) { // is unique
uniqArr.push(instance);
}
instance[expando] = true;
}
// clean up expandos
for (var j = 0; j < len; j++) {
delete arr[j][expando];
}
return uniqArr;
}
function uniq4(arr){
var items = [];
var unique = new WeakMap();
arr.forEach(function(item){
if(!unique.has(item)) {
unique.set(item, true);
items.push(item);
}
});
return items;
}
function uniq5(arr){
var items = [];
var unique = new Map();
arr.forEach(function(item){
if(!unique.has(item)) {
unique.set(item, true);
items.push(item);
}
});
return items;
}
function uniq6(a) {
var add;
var arr = [];
for(var i = 0, l = a.length; i < l; i++) {
add = 1;
for(var o = 0, p = arr.length; o < p; o++) {
if (a[i] === arr[o]) {
add = 0;
}
}
if (add) {
arr.push(a[i]);
}
}
return arr;
}
console.assert(result.length === Math.floor(window.N/2) + 3);
Ready to run.
Test | Ops/sec | |
---|---|---|
Unique using indexOf and O(N^2) |
| ready |
Unique using Set |
| ready |
Unique using expando prop |
| ready |
Unique using WeakMap |
| ready |
Unique using Map |
| ready |
Ben |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.