現在關于 React 最新 v16 版本新特性的宣傳、講解已經“鋪天蓋地”了。你最喜歡哪一個 new feature?
截至目前,組件構建方式已經琳瑯滿目。那么,你考慮過他們的性能對比嗎?這篇文章,聚焦其中一個小細節,進行對比,望讀者參考的同時,期待大神斧正。
從 React.PureComponent 說起
先上結論:在我們的測試當中,使用 React.PureComponent 能夠提升 30% JavaScript 執行效率。測試場景是反復操作數組,這個“反復操作”有所講究,我們計劃持續不斷地改變數組的某一項(而不是整個數組的大范圍變動)。
線上參考地址: 請點擊這里
那么這樣的場景,作為開發者有必要研究嗎?如果你的應用并不涉及到高頻率的更新數組某幾項,那么大可不必在意這些性能的微妙差別。但是如果存在一些“實時更新”的場景,比如:
- 用戶輸入改變數組(點贊者顯示);
- 輪詢(股票實時);
- 推更新(比賽比分實時播報);
那么就需要進行考慮。我們定義:changedItems.length / array.length 比例越小,本文所涉及的性能優化越應該實施,即越有必要使用 React.PureComponent。
代碼和性能測試
在使用 React 開發時,相信很多開發者在搭配函數式的狀態管理框架 Redux 使用。Redux reducers 作為純函數的同時,也要保證 state 的不可變性,在我們的場景中,也就是說在相關 action 被觸發時,需要返回一個新的數組。
const users = (state, action) => {
if (action.type === 'CHANGE_USER_1') {
return [action.payload, ...state.slice(1)]
}
return state
}
如上代碼,當 CHANGE_USER_1 時,我們對數組的第一項進行更新,使用 slice 方法,不改變原數組的同時返回新的數組。
我們設想所有的 users 數組被 Users 函數式組件渲染:
import User from './User'
const Users = ({users}) =>
<div>
{
users.map(user => <User {...user} />
}
</div>
問題的關鍵在于:users 數組作為 props 出現,當數組中的第 K 項改變時,所有的 <User> 組件都會進行 reconciliation 的過程,即使非 K 項并沒有發生變化。
這時候,我們可以引入 React.PureComponent,它通過淺對比規避了不必要的更新過程。即使淺對比自身也有計算成本,但是一般情況下這都不值一提。
以上內容其實已經“老生常談”了,下面直接進入代碼和性能測試環節。
我們渲染了一個有 200 項的數組:
const arraySize = 200;
const getUsers = () =>
Array(arraySize)
.fill(1)
.map((_, index) => ({
name: 'John Doe',
hobby: 'Painting',
age: index === 0 ? Math.random() * 100 : 50
}));
注意在 getUsers 方法中,關于 age 屬性我們做了判斷,保證每次調用時,getUsers 返回的數組只有第一項的 age 屬性不同。
這個數組將會觸發 400 次 re-renders 過程,并且每一次只改變數組第一項的一個屬性(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
`);
}
}
為此,我們采用三種方式設計 <User> 組件。
函數式方式
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>
);
}
}
經典 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>
);
}
}
同時,在不同的瀏覽器環境下,我得出:
- Firefox 下,PureComponent 收益 30%;
- Safari 下,PureComponent 收益 6%;
- Chrome 下,PureComponent 收益 15%;
測試硬件環境:
最終結果:
最后,送給大家魯迅先生的一句話:
“Early optimization is the root of all evil”?- 魯迅