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

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

    I have created the performance benchmarks for multiple immutable libraries, the script and results are located inside the immutable-assign (GitHub project), which shows that immutable.js is optimized for write operations, faster than Object.assign(), however, it is slower for read operations. Following are the summary of the benchmarks results:

    -- Mutable
    Total elapsed = 50 ms (read) + 53 ms (write) = 103 ms.
    
    -- Immutable (Object.assign)
    Total elapsed = 50 ms (read) + 2149 ms (write) = 2199 ms.
    
    -- Immutable (immutable.js)
    Total elapsed = 638 ms (read) + 1052 ms (write) = 1690 ms.
    
    -- Immutable (seamless-immutable)
    Total elapsed = 31 ms (read) + 91302 ms (write) = 91333 ms.
    
    -- Immutable (immutable-assign (created by me))
    Total elapsed = 50 ms (read) + 2173 ms (write) = 2223 ms.
    

    Therefore, whether to use immutable.js or not will depend on the type of your application, and its read to write ratio. If you have lots of write operations, then immutable.js will be a good option.

    Premature optimization is the root of all evil

    Ideally, you should profile your application before introducing any performance optimization, however, immutability is one of those design decision must be decided early. When you start using immutable.js, you need to use it throughout your entire application to get the performance benefits, because interop with plain JS objects using fromJS() and toJS() is very costly.

提交回复
热议问题