Created
February 25, 2020 13:47
-
-
Save syaau/e9b991e55aed8c249fa5a86511f77ca5 to your computer and use it in GitHub Desktop.
Check spread operator vs Object.assign performance (with varying key sizes)
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
// 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); |
Author
syaau
commented
Feb 25, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment