Object.assign performance on using with collections.

With ES2016 we have many things write shorter and look better.

Small experiment of using Object.assign.

I have tried to use it in reduce functions that’s convert collection to index object. For example to index by id with and without Object.assign:

collection.reduce((items, item) => {  
  items[item.id] = item;
  return items;
}, {});
collection.reduce((items, item) => Object.assign(items, { [item.id]: item }), {});  

What about performance?

I use simple console test with console.time() for syncronious operation to check their performance.

Example test

First lets generate 10000 random items collection:

const collection = [...Array(10000)]  
  .map((item, index) => ({id: index, value: Math.random()}));
Count reduce execution time without Object.assign:

collection.reduce((col, item) => {  
  col[item.id] = item;
  return col;
}, {});

Result test: 0.797119140625ms

Count reduce execution with Object.assign:

collection.reduce((col, item) => Object.assign(col, { [item.id]: item }), {});

Result: test: 18.228271484375ms


Object.assign method is still not optimised well and you should carefully use it on huge collections.

Tested in Chrome Canary version 59.0.3035.0

No comments

Leave a comment!

Your email address will not be published. Required fields are marked *