Skip to content

Instantly share code, notes, and snippets.

@syaau
Created February 25, 2020 13:47
Show Gist options
  • Save syaau/e9b991e55aed8c249fa5a86511f77ca5 to your computer and use it in GitHub Desktop.
Save syaau/e9b991e55aed8c249fa5a86511f77ca5 to your computer and use it in GitHub Desktop.
Check spread operator vs Object.assign performance (with varying key sizes)
// Test object recreate speed on large objects vs small objects
function createObject(propsCount) {
const obj = {};
for (let i = 0; i < propsCount; i += 1) {
obj[`p${i}`] = i;
}
return obj;
}
function time(label, fn, iterations) {
const start = Date.now();
for (let i = 0; i < iterations; i++) {
fn();
}
const interval = Date.now() - start;
console.log(label, 'Time taken', interval, 'ms', ' PerIteration', interval * 1000 / iterations, 'µs');
}
function spread(obj) {
return { ...obj, k: 20 };
}
const k = { k: 20 };
function assign(obj) {
return Object.assign({}, obj, k);
}
const large = createObject(200);
const small = createObject(50);
const iterations = 10000;
setTimeout(() => {
time('Large Spread', () => spread(large), iterations);
time('Small Spread', () => spread(small), iterations);
time('Large assign', () => assign(large), iterations);
}, 1000);
@syaau
Copy link
Author

syaau commented Feb 25, 2020

Object.assign is much faster, specially with higher number of keys

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment