按照官网的定义, Immutable Data是指一旦被创造后,就不能够被改变的数据。javascript
JavaScript提供三种不一样的值比较操做:java
三者区别以下:react
那么,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.js和Lodash都有一个名为_.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
恩,达到了咱们想要的效果。性能
众所周知,react性能优化的核心在于处理shouldComponentUpdate
方法来避免没必要要的渲染。虽然react提供了PureComponent,但它实质只是浅比较,没法很好地处理对象的比较,因此仍是不能解决重复渲染的问题。优化
这个时候,immutable.js
应运而生,它能够完美地解决这个问题,极大地提升react应用的性能。spa