Skip to content

Instantly share code, notes, and snippets.

@saml
Created April 28, 2017 16:31
Show Gist options
  • Select an option

  • Save saml/af132eab2be2657f421be29cc98290fc to your computer and use it in GitHub Desktop.

Select an option

Save saml/af132eab2be2657f421be29cc98290fc to your computer and use it in GitHub Desktop.
const randomstring = require('randomstring');
const Benchmark = require('benchmark');
const numOfKeys = parseInt(process.argv[2], 10) || 1000000;
const keyLength = 13;
console.time('keygen');
const randomKeys = Array.from({length: numOfKeys}, () => randomstring.generate(keyLength));
console.timeEnd('keygen');
const obj = {};
const set = new Set();
const map = new Map();
function objSet() {
randomKeys.forEach(k => {
obj[k] = 1;
});
}
function objGet() {
let x;
randomKeys.forEach(k => {
x = obj[k];
});
}
function setSet() {
randomKeys.forEach(k => {
set.add(k);
});
}
function setGet() {
let x;
randomKeys.forEach(k => {
x = set.has(k);
});
}
function mapSet() {
randomKeys.forEach(k => {
map.set(k, 1);
});
}
function mapGet() {
let x;
randomKeys.forEach(k => {
x = map.get(k);
});
}
new Benchmark.Suite()
.add('obj#set', objSet)
.add('map#set', mapSet)
.add('set#set', setSet)
.add('obj#get', objGet)
.add('map#get', mapGet)
.add('set#get', setGet)
.on('cycle', (ev) => {
console.log(String(ev.target));
})
.on('complete', function() {
console.log(`Fastest ${this.filter('fastest').map('name')}`);
})
.run({async: true});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment