Skip to content

Instantly share code, notes, and snippets.

@usualoma
Created February 21, 2022 22:58
Show Gist options
  • Save usualoma/6d22fdb1b64e7ae8f4d6fe2d204b9208 to your computer and use it in GitHub Desktop.
Save usualoma/6d22fdb1b64e7ae8f4d6fe2d204b9208 to your computer and use it in GitHub Desktop.
import Benchmark from 'benchmark'
const suite = new Benchmark.Suite()
const obj = {
a: 1,
b: 2,
c: 3,
}
const obj2 = {
a: 1,
b: 2,
c: 3,
}
obj2.keys = Object.keys(obj2)
const assoc = [
["a", 1],
["b", 2],
["c", 3],
]
suite
.add('a', () => {
const o = {}
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
o[keys[i]] = obj[keys[i]]
}
})
.add('b', () => {
const o = {}
for (let i = 0; i < assoc.length; i++) {
o[assoc[i][0]] = assoc[i][1]
}
})
.add('c', () => {
const o = {}
for (let i = 0; i < obj2.keys.length; i++) {
o[obj2.keys[i]] = obj2[obj2.keys[i]]
}
})
.on('cycle', (event) => {
console.log(String(event.target))
})
.on('complete', function () {
console.log(`Fastest is ${this.filter('fastest').map('name')}`)
})
.run({ async: true })
a x 8,140,534 ops/sec ±2.78% (82 runs sampled)
b x 12,668,517 ops/sec ±1.82% (85 runs sampled)
c x 9,372,974 ops/sec ±3.00% (85 runs sampled)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment