Advantages of using immutable.js over Object.assign or spread operators

前端 未结 6 983
天涯浪人
天涯浪人 2021-02-02 08:55

So far most of \"starter boilerplates\" and some posts about react / redux I\'ve seen encourage usage of immutable.js to address mutability. I personally rely on Object.as

6条回答
  •  别那么骄傲
    2021-02-02 09:51

    This is all about efficiency.

    Persistent Data Structures

    A persistent data structure keeps previous versions of itself when it is mutated by always yielding a new data structure. To avoid expensive cloning only the difference to the previous data structure is stored, whereas the intersection is shared between them. This strategy is called structural sharing. Hence persistent data structures are much more efficient then cloning with Object.assign or the spread operator.

    Drawbacks of persistent data structures in Javascript

    Unfortunately Javascript doesn't support persistent data structures natively. That is the reason immutable.js exists and that its objects differ greatly from plain old Javascript Objects. This leads to more verbose code and a lot of conversions of persistent data structures to native Javascript data structures.

    The crucial question

    When does the benefits of immutable.js's structural sharing (efficiency) exceed its disadvantages (verbosity, conversions)?

    I guess the library pays off only in large projects with numerous and extensive objects and collections, when cloning of whole data structures and garbage collection gets more expensive.

提交回复
热议问题