Performance and Transient Changes

Performance

Immutable data structures often have a performance penalty due to the costs of allocation new memory and copying data. Consider these two examples, one which uses a mutable array and one which uses an Immutable.js collection.

Mutable

  1. const list = [];
  2. let val = "";
  3. Immutable.Range(0, 1000000)
  4. .forEach(function() {
  5. val += "concatenation";
  6. list.push(val);
  7. });

Immutable

  1. const init = {
  2. list: Immutable.List(),
  3. val: ""
  4. };
  5. const list = Immutable.Range(0, 1000000)
  6. .reduce(function(reduced) {
  7. var next = reduced.val + "concatenation";
  8. return {
  9. list: reduced.list.push(next),
  10. val: next
  11. };
  12. }, init).list

Here the fully immutable code runs around 90% slower than the mutable code! While immutable data can make code much easier to reason about, there is definitely a cost associated with that decision. As we can see here for iterative concat, this can have a major impact on usability. Fortunately, Immutable.js provides some features where the performance costs can be mitigated.

Persistent Data Structures and Transient Changes

Immutable data structures are also sometimes referred to as persistent data structures, since their values persist for their lifetime. Immutable.js provides the option for transient changes: operations during which an immutable data structure can perform mutable changes locally while returning an immutable result. This is one approach to solving the performance issues we encountered earlier. Let's revisit the immutable case outlined in the performance example, but using a transient data structure this time:

  1. import * as Immutable from 'immutable';
  2. let list = list.withMutations(mutableList => {
  3. let val = "";
  4. return Immutable.Range(0, 1000000)
  5. .forEach(() => {
  6. val += "concatenation";
  7. mutableList.push(val);
  8. });
  9. });
  10. console.log(list.size); // writes 1000000
  11. list.push('');
  12. console.log(list.size); // writes 1000000

This transient list builder is still much slower than our fully mutable implementation but much faster than our fully immutable version.

原文: https://angular-2-training-book.rangle.io/handout/immutable/immutable-js/performance_transient_changes.html