[js] answer the pros and cons of immutability (#211)

* Update: What are the pros and cons of immutability?

add the pros and cons of immutability

* Update javascript-questions.md
This commit is contained in:
Felix Häberle 2019-11-24 19:42:48 +01:00 committed by Yangshun Tay
parent b37787ac7f
commit 526774b786
1 changed files with 15 additions and 2 deletions

View File

@ -1012,11 +1012,24 @@ Freezing an object does not allow new properties to be added to an object and pr
**Pros**
TODO
* Easier change detection - Object equality can be determined in a performant and easy manner through referential equality. This is useful for comparing object differences in React and Redux.
* Programs with immutable objects are less complicated to think about, since you don't need to worry about how an object may evolve over time.
* Defensive copies are no longer necessary when immutable objects are returning from or passed to functions, since there is no possibility an immutable object will be modified by it.
* Easy sharing via references - One copy of an object is just as good as another, so you can cache objects or reuse the same object multiple times.
* Thread-safe - Immutable objects can be safely used between threads in a multi-threaded environment since there is no risk of them being modified in other concurrently running threads.
* Using libraries like ImmmutableJS, objects are modified using structural sharing and less memory is needed for having multiple objects with similar structures.
**Cons**
TODO
* Naive implementations of immutable data structures and its operations can result in extremely poor performance because new objects are created each time. It is recommended to use libraries for efficient immutable data structures and operations that leverage on structural sharing.
* Allocation (and deallocation) of many small objects rather than modifying existing ones can cause a performance impact. The complexity of either the allocator or the garbage collector usually depends on the number of objects on the heap.
* Cyclic data structures such as graphs are difficult to build. If you have two objects which can't be modified after initialization, how can you get them to point to each other?
###### References
- https://stackoverflow.com/questions/1863515/pros-cons-of-immutability-vs-mutability
[[↑] Back to top](#js-questions)
#### How can you achieve immutability in your own code?