Persistent and Transient Data Structures

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 data structures, which is a mutable version of a persistent data structure during a transformation stage and returning a new immutable version upon completion. 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 = Immutable.List();
  3. list = list.withMutations(mutableList => {
  4. let val = "";
  5. return Immutable.Range(0, 1000000)
  6. .forEach(() => {
  7. val += "concatenation";
  8. mutableList.push(val);
  9. });
  10. });
  11. console.log(list.size); // writes 1000000
  12. list.push('');
  13. console.log(list.size); // writes 1000000

As we can see in this performance test, the transient list builder was still a lot slower than the fully mutable version, but much faster than the fully immutable version. Also, if you pass the mutable array to Immutable.List or Immutable.fromJS, you’ll find the transient version closes the performance gap. The test also shows how slow Object.freeze can be compared to the other three.