Performance boosting with immutable data and OnPush - FadiZahhar/switchingtoangular2 GitHub Wiki
The last change detection strategy that we are going to describe is OnPush. It is extremely useful when the result that the given component produces depends only on its inputs. In such cases, we can pass immutable data to the inputs in order to make sure that it will not be mutated by any other component. This way, by having a component that depends only on its immutable inputs, we can make sure that it produces different user interfaces only once it receives different inputs (that is, different reference). In this section, we are going to apply the OnPush strategy on the TodoList component. Since it depends only on its inputs (the todos input), we want to make sure that its change detection will be performed only once it receives a new reference of the todos collection. The essence of immutable data is that it cannot change. This means that once we add a new to-do item to the todos collection, we cannot change it; instead, the add (or in our case, push) method will return a new collection—a copy of the initial collection with the new item included. This may seem like a huge overhead—to copy the entire collection on each change. In big applications, this may have a big performance impact. However, we don't need to copy the entire collection. There are libraries that implement immutable data structure using smarter algorithms: persistent data structures. Persistent data structures are out of the scope of the current content. Further information about them can be found in most computer science textbooks for advanced data structures. The good thing is that we don't have to understand their implementation in depth in order to use them! There is a library called Immutable.js that implements a few commonly used immutable data structures. In our case, we are going to use the immutable list. Generally, the immutable list behaves just like a normal list, but on each operation that is supposed to mutate it, it returns a new list.