使用OnPush和immutable.js來提升angular的效能
阿新 • • 發佈:2021-01-20
angular裡面變化檢測是非常頻繁的發生的,如果你像下面這樣寫程式碼
<div>
{{hello()}}
</div>
則每次變化檢測都會執行hello函式,如果hello函式十分耗時,則會出現佔用CPU高的問題。
這時,推薦使用OnPush策略和immutable.js來提升angular應用的效能。
OnPush策略可以阻止angular變化檢測傳入元件,這樣每次變化檢測不會進到你的元件裡面來呼叫hello函式。
引入immutable.js的作用是為了更加方便的使用OnPush策略。
看下immutable.js的例子
const list1 = Immutable.List([ {a: 1}, {a: 2} ]); const list2= list1.push({a: '3'}); console.log(list1 === list2); // false console.log(list1.get(0) === list2.get(0)); // true const list3 = list2.pop(); console.log(list1 === list3); // false const map1 = Immutable.Map({ a: 1, b: 2, c: 3 }); const map2 = map1.set('b', 50); console.log(map1 === map2); //false const map3 = map1.set('b', 2); console.log(map1 === map3); // true const map4 = map2.set('b', 2); console.log(map1 === map4); // false
這樣在父元件裡只需要如此寫
export class AppComponent { ii = ''; list = List([{label: 'default'}]); add() { if (this.ii) { this.list = this.list.push({label: this.ii}); this.ii = ''; } } }
子元件HTML程式碼
<div> {{hello()}} </div> <ul *ngFor="let item of list"> <li>{{item.label}}</li> </ul>
不需要trackby,因為預設trackby就是比較元素相等,immutable.js數組裡不變的元素就是相等的,少寫一些程式碼啦。