When should I use `withMutations` on a map in Immutable.js

immutable.js

I have a series of mutations to make on my Immutable.js map.

At what point should I prefer using withMutations rather than creating intermediate immutable maps?

From the Immutable.js docs:

If you need to apply a series of mutations to produce a new immutable
Map, withMutations() creates a temporary mutable copy of the Map which
can apply mutations in a highly performant manner. In fact, this is
exactly how complex mutations like merge are done.

But, where is the line? If I need to make two mutations should I use withMutations?

Best Solution

You should use withMutations when you want to group several changes on an object.

Because each change creates a clone, several changes in a row cause several clones. Use withMutations to apply several changes then clone once at the end. A clone at every step means that you are reading the entire list for each change, which makes it an n^2 operation. Using the mutatable version leaves it at just N.

This can create a massive performance hit if you just start doing things willy nilly like the other answer suggests. The kicker is it might not matter on a small test of data, but what happens if you push it live and then do a large scale operation on an array with 300,000 pieces of data instead of your test data which only has 100 elements. In your test data, you did 10,000 copies of which you might not notice. In production you would do 900,000,000,00 copies which might light your computer on fire (not really, but you would freeze the tab).

I wrote a demo demonstrating the performance difference http://jsperf.com/with-out-mutatable