Batching mutations
If a tree falls in the woods, does it make a sound?
If a pure function mutates some local data in order to produce an immutable return value, is that ok?
— Rich Hickey, Clojure
Applying a mutation to create a new immutable object results in some overhead,
which can add up to a minor performance penalty. If you need to apply a series
of mutations locally before returning, Immutable.js gives you the ability to
create a temporary mutable (transient) copy of a collection and apply a batch of
mutations in a performant manner by using withMutations. In fact, this is
exactly how Immutable.js applies complex mutations itself.
As an example, building list2 results in the creation of 1, not 3, new
immutable Lists.
Which methods can be batched
Important: only a select few methods can be used inside withMutations,
including set, push and pop. These methods can be applied directly against
a persistent data structure, where other methods like map, filter, sort
and splice will always return new immutable data structures and never mutate a
mutable collection.
asMutable and asImmutable
Immutable.js also provides asMutable and asImmutable, but only encourages
their use when withMutations will not suffice. Use caution not to return a
mutable copy, which could result in undesired behavior.