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

前端 未结 6 964
天涯浪人
天涯浪人 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:46

    I think the main advantage of ImmutableJs is in its data structures and speed. Sure, it also enforces immutability, but you should be doing that anyways, so that's just an added benefit.

    For example, say you have a very large object in your reducer and you want to change a very small part of that object. Because of immutability, you can't change the object directly, but you must create a copy of the object. You do that by copying everything (in ES6 using the spread operator).

    So what's the problem? Copying very large objects is very slow. Data structures in ImmutableJS do something called structural sharing where you really only change the data you want. The other data that you aren't changing is shared between the objects, so it doesn't get copied.

    The result of this are highly efficient data structures, with fast writes.

    ImmutableJS also offers easy comparisons for deep objects. For example

    const a = Immutable.Map({ a: Immutable.Map({ a: 'a', b: 'b'}), b: 'b'});
    const b = Immutable.Map({ a: Immutable.Map({ a: 'a', b: 'b'}), b: 'b'});
    
    console.log(a.equals(b)) // true 
    

    Without this, you'd need some sort of deep comparison function, that would also take a lot of time, whereas the root nodes here contain a hash of the entire datastructure (don't quote me on this, this is how I remember it, but the comparisons are always instant), so comparisons are always O(1) i.e. instant, regardless of object size.

    This can be especially useful in the React shouldComponentUpdate method, where you can just compare the props using this equals function, which runs instantaneously.

    Of course, there are also downsides, if you mix immutablejs structures and regular objects, it can be hard to tell what's what. Also your codebase is littered with the immutableJS syntax, which is different from regular Javascript.

    Another downside is that if you aren't going to use deeply nested objects, it is going to be a bit slower than plain old js, since the data structures do have some overhead.

    Just my 2 cents.

提交回复
热议问题