Created
January 7, 2018 10:11
-
-
Save shamasis/8946f482829b7d486229b0709e17a4bc to your computer and use it in GitHub Desktop.
Benchmark ES6 Set vs Object to filter unique strings from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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