Created
December 20, 2022 23:49
-
-
Save inaiat/e9fadac649335b3be335f541ef9eacc0 to your computer and use it in GitHub Desktop.
benchmark merge object
This file contains hidden or 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
import _ from 'lodash-es' | |
import Benchmark from 'benchmark' | |
function getItems(count) { | |
let id = 1 | |
return _.times(count, () => ( | |
{ | |
name: 'city' + id++, | |
visited: true, | |
id, | |
})) | |
} | |
function assert(value) { | |
if (!value) { | |
throw 'assertion failed' | |
} | |
} | |
const benchmarks = { | |
'merge reduce spread'(items) { | |
const result = items.reduce((_, value) => ({...value, population: value.id})) | |
assert(result.population === items[items.length - 1].id) | |
}, | |
'merge reduce object assign'(items) { | |
const result = items.reduce((_, value) => Object.assign(value, {population: value.id})) | |
assert(result.population === items[items.length - 1].id) | |
}, | |
'merge for spread'(items) { | |
let result = {} | |
for (const item of items) { | |
result = {...item, population: item.id} | |
} | |
assert(result.population === items[items.length - 1].id) | |
}, | |
'merge for object assign'(items) { | |
let result = {} | |
for (const item of items) { | |
result = Object.assign(item, {population: item.id}) | |
} | |
assert(result.population === items[items.length - 1].id) | |
}, | |
} | |
function runSeries(counts) { | |
const seriesResults = {} | |
return counts.map( | |
count => () => runSuite(count) | |
.then(results => { | |
_.forEach(results, (result, name) => { | |
if (!seriesResults[name]) { | |
seriesResults[name] = [] | |
} | |
seriesResults[name].push([ | |
count, | |
result, | |
]) | |
}) | |
}), | |
).reduce( | |
(acc, benchmark) => acc.then(benchmark), | |
Promise.resolve(), | |
).then(() => seriesResults) | |
} | |
function runSuite(count) { | |
console.log(`benchmark with ${count} items`) | |
return new Promise((resolve, reject) => { | |
const items = getItems(count) | |
const suite = new Benchmark.Suite() | |
_.forEach(benchmarks, (run, name) => { | |
suite.add(name, run.bind(null, items), | |
{ | |
maxTime: 0, | |
minSamples: 30, | |
}, | |
) | |
}) | |
suite | |
.on('error', reject) | |
.on('cycle', event => { | |
console.log(String(event.target)) | |
}) | |
.on('complete', function () { | |
console.log('Fastest is ' + this.filter('fastest').map('name')) | |
resolve(this.reduce((results, benchmark) => { | |
results[benchmark.name] = Math.round(benchmark.hz) | |
return results | |
}, {})) | |
}) | |
.run({async: true}) | |
}) | |
} | |
runSeries([2, 10, 50, 100]).then(results => { | |
global.results = results | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment