I've also been trying to decide when it's best to use withMutations vs not. So far I have always been using withMutations when I need to loop through a list of items with unknown size n
, and perform n
mutations on a single map.
Example:
updateItems(state, items) {
return state.withMutations(state => {
items.forEach(item => {
state.set(item.get('id'), item);
});
});
}
What I wanted to know, is if I should use withMutations on a smaller known set of updates, or if I should just chain set
.
Example:
setItems(state, items, paging) {
return state.set('items', items).set('paging', paging);
}
Or:
setItems(state, items, paging) {
return state.withMutations(state => {
state.set('items', items);
state.set('paging', paging);
});
}
In this case, I would prefer to use the first option (chained set
calls), but I wasn't sure of the performance impact. I created this jsPerf to test some similar cases: http://jsperf.com/immutable-batch-updates-with-mutations.
I ran batches of 2 updates and 100 updates, using an empty inital map, and a complex initial map, both using withMutations
and just chaining set
.
The results seem to show that withMutations
was always better on the 100 update case, regardless of initial map. withMutations
performed marginally better on the 2 update case when starting with an empty map. However, just chaining 2 set
calls performed better when starting with a complex map.