immutable.js初识

介绍

按照官网的定义, Immutable Data是指一旦被创造后,就不能够被改变的数据。javascript

相等性判断

JavaScript提供三种不一样的值比较操做:java

  1. 严格相等 ("triple equals" 或 "identity"),使用 === 
  2. 宽松相等 ("double equals") ,使用 ==
  3. Object.is( ECMAScript 2015/ ES6 新特性)

三者区别以下:react

aaa.png

那么,javascript是怎么对两个对象进行比较的呢?git

var person1 = {
  age: 27, 
  gender: "male",
  education: {major:"math",school:"Harvard"}
};

var person2 = {
  age: 27, 
  gender: "male",
  education: {major:"math",school:"Harvard"}
};

console.log(person1 == person2); //false
console.log(person1 === person2); //false
console.log(Object.is(person1,person2)); //false

虽然,person1和person2的属性是彻底同样的,可是person1和person2相等性判断为false。由于对象是经过指针指向的内存中的地址来比较的。github

不少场景下,对于属性相同的对象,咱们但愿相等性判断为true。Underscore.jsLodash都有一个名为_.isEqual()方法,用来处理深度对象的比较。大体思路是递归查找对象的属性进行值比较(具体实现推荐这篇文章:https://github.com/hanzichi/u...)。固然了,对象层级越深,比较越耗时。性能优化

相比之下,immutable.js使用了 Structural Sharing(结构共享),特别擅长处理对象的比较,性能很是好。上面的代码,让咱们换成immutable.js来表达:ide

const person1 = Immutable.Map( {
      age: 27, 
      gender: "male",
      education: Immutable.Map({
        major:"math",
        school:"Harvard"
      })
});

const person2 = Immutable.Map( {
      age: 27, 
      gender: "male",
      education: Immutable.Map({
        major:"math",
        school:"Harvard"
      })
});

const person3 = person1.setIn(["education","major"], "english"); //person3专业为english

console.log(Immutable.is(person1, person2));//true
console.log(Immutable.is(person1, person3));//false

恩,达到了咱们想要的效果。性能

immutable.js之于react的好处

众所周知,react性能优化的核心在于处理shouldComponentUpdate方法来避免没必要要的渲染。虽然react提供了PureComponent,但它实质只是浅比较,没法很好地处理对象的比较,因此仍是不能解决重复渲染的问题。优化

这个时候,immutable.js应运而生,它能够完美地解决这个问题,极大地提升react应用的性能。spa

相关文章
相关标签/搜索