Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamasis/8946f482829b7d486229b0709e17a4bc to your computer and use it in GitHub Desktop.
Save shamasis/8946f482829b7d486229b0709e17a4bc to your computer and use it in GitHub Desktop.
Benchmark ES6 Set vs Object to filter unique strings from an array
const
_ = require('lodash'),
Benchmark = require('benchmark'),
suite = new Benchmark.Suite,
result = [],
seedSize = 10000,
seedData = Array(seedSize).fill().map(() => String(Math.round(Math.random() * seedSize)));
suite
.add('creating unique elements from Set', function () {
let set,
arr;
set = new Set();
seedData.forEach((str) => set.add(str));
arr = [...set];
})
.add('creating unique elements from Object', function () {
let obj,
arr;
obj = new Object();
seedData.forEach((str) => obj[str] = undefined);
arr = Object.keys(obj);
})
.add('creating unique elements using Array', function () {
let arr = [];
for (let i = 0, ii = seedData.length; i < ii; i++) {
if (arr.indexOf(seedData[i]) === -1) {
arr.push(seedData[i]);
}
}
})
.add('creating unique elements using lodash (lol)', function () {
let arr = _.uniq(seedData);
})
.on('error', (event) => console.log(event.target.error))
.on('cycle', (event) => {
console.log(String(event.target))
result.push(event.target);
})
.on('complete', function () {
console.log(`\nFastest is ${this.filter('fastest').map('name')}`);
result
.map((bench) => ({ name: bench.name, mean: bench.stats.mean}))
.sort((a, b) => a.mean > b.mean)
.forEach((bench, index) => {
console.log(` ${index+1}. ${bench.name}`);
});
})
.run({ 'async': true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment