現(xiàn)在關(guān)于 React 最新 v16 版本新特性的宣傳、講解已經(jīng)“鋪天蓋地”了愕撰。你最喜歡哪一個 new feature刹衫?
截至目前,組件構(gòu)建方式已經(jīng)琳瑯滿目搞挣。那么带迟,你考慮過他們的性能對比嗎?這篇文章囱桨,聚焦其中一個小細節(jié)仓犬,進行對比,望讀者參考的同時舍肠,期待大神斧正搀继。
從 React.PureComponent 說起
先上結(jié)論:在我們的測試當(dāng)中窘面,使用 React.PureComponent 能夠提升 30% JavaScript 執(zhí)行效率。測試場景是反復(fù)操作數(shù)組律歼,這個“反復(fù)操作”有所講究民镜,我們計劃持續(xù)不斷地改變數(shù)組的某一項(而不是整個數(shù)組的大范圍變動)。
線上參考地址: 請點擊這里
那么這樣的場景险毁,作為開發(fā)者有必要研究嗎制圈?如果你的應(yīng)用并不涉及到高頻率的更新數(shù)組某幾項,那么大可不必在意這些性能的微妙差別畔况。但是如果存在一些“實時更新”的場景鲸鹦,比如:
- 用戶輸入改變數(shù)組(點贊者顯示);
- 輪詢(股票實時)跷跪;
- 推更新(比賽比分實時播報)馋嗜;
那么就需要進行考慮。我們定義:changedItems.length / array.length 比例越小吵瞻,本文所涉及的性能優(yōu)化越應(yīng)該實施葛菇,即越有必要使用 React.PureComponent。
代碼和性能測試
在使用 React 開發(fā)時橡羞,相信很多開發(fā)者在搭配函數(shù)式的狀態(tài)管理框架 Redux 使用眯停。Redux reducers 作為純函數(shù)的同時,也要保證 state 的不可變性卿泽,在我們的場景中莺债,也就是說在相關(guān) action 被觸發(fā)時,需要返回一個新的數(shù)組签夭。
const users = (state, action) => {
if (action.type === 'CHANGE_USER_1') {
return [action.payload, ...state.slice(1)]
}
return state
}
如上代碼齐邦,當(dāng) CHANGE_USER_1 時,我們對數(shù)組的第一項進行更新第租,使用 slice 方法措拇,不改變原數(shù)組的同時返回新的數(shù)組。
我們設(shè)想所有的 users 數(shù)組被 Users 函數(shù)式組件渲染:
import User from './User'
const Users = ({users}) =>
<div>
{
users.map(user => <User {...user} />
}
</div>
問題的關(guān)鍵在于:users 數(shù)組作為 props 出現(xiàn)慎宾,當(dāng)數(shù)組中的第 K 項改變時丐吓,所有的 <User> 組件都會進行 reconciliation 的過程,即使非 K 項并沒有發(fā)生變化璧诵。
這時候汰蜘,我們可以引入 React.PureComponent,它通過淺對比規(guī)避了不必要的更新過程之宿。即使淺對比自身也有計算成本族操,但是一般情況下這都不值一提。
以上內(nèi)容其實已經(jīng)“老生常談”了,下面直接進入代碼和性能測試環(huán)節(jié)色难。
我們渲染了一個有 200 項的數(shù)組:
const arraySize = 200;
const getUsers = () =>
Array(arraySize)
.fill(1)
.map((_, index) => ({
name: 'John Doe',
hobby: 'Painting',
age: index === 0 ? Math.random() * 100 : 50
}));
注意在 getUsers 方法中泼舱,關(guān)于 age 屬性我們做了判斷,保證每次調(diào)用時枷莉,getUsers 返回的數(shù)組只有第一項的 age 屬性不同娇昙。
這個數(shù)組將會觸發(fā) 400 次 re-renders 過程,并且每一次只改變數(shù)組第一項的一個屬性(age):
const repeats = 400;
componentDidUpdate() {
++this.renderCount;
this.dt += performance.now() - this.startTime;
if (this.renderCount % repeats === 0) {
if (this.componentUnderTestIndex > -1) {
this.dts[componentsToTest[this.componentUnderTestIndex]] = this.dt;
console.log(
'dt',
componentsToTest[this.componentUnderTestIndex],
this.dt
);
}
++this.componentUnderTestIndex;
this.dt = 0;
this.componentUnderTest = componentsToTest[this.componentUnderTestIndex];
}
if (this.componentUnderTest) {
setTimeout(() => {
this.startTime = performance.now();
this.setState({ users: getUsers() });
}, 0);
} else {
alert(`
Render Performance ArraySize: ${arraySize} Repeats: ${repeats}
Functional: ${Math.round(this.dts.Functional)} ms
PureComponent: ${Math.round(this.dts.PureComponent)} ms
Component: ${Math.round(this.dts.Component)} ms
`);
}
}
為此笤妙,我們采用三種方式設(shè)計 <User> 組件冒掌。
函數(shù)式方式
export const Functional = ({ name, age, hobby }) => (
<div>
<span>{name}</span>
<span>{age}</span>
<span>{hobby}</span>
</div>
);
PureComponent 方式
export class PureComponent extends React.PureComponent {
render() {
const { name, age, hobby } = this.props;
return (
<div>
<span>{name}</span>
<span>{age}</span>
<span>{hobby}</span>
</div>
);
}
}
經(jīng)典 class 方式
export class Component extends React.Component {
render() {
const { name, age, hobby } = this.props;
return (
<div>
<span>{name}</span>
<span>{age}</span>
<span>{hobby}</span>
</div>
);
}
}
同時,在不同的瀏覽器環(huán)境下蹲盘,我得出:
- Firefox 下股毫,PureComponent 收益 30%;
- Safari 下召衔,PureComponent 收益 6%铃诬;
- Chrome 下,PureComponent 收益 15%苍凛;
測試硬件環(huán)境:
最終結(jié)果:
最后趣席,送給大家魯迅先生的一句話:
“Early optimization is the root of all evil”?- 魯迅