前言
去年開始用 React 開發,對於效能上跟畫面 render 的速度其實一直沒有搞得很清楚,也不知道該如何去觀察,最近因為專案的開發,面對巨量的資料,發生了效能的問題,發現有這個工具可以來監測究竟頁面上每個 component 的 render 花了多少時間。
整理一下從 React 官網對於 React Profiler 的說明跟用法。
官網的頁面跟現行的相比在圖片顯示上有點不一樣,不過大致上都還是差不多的。
安裝
前往 google chrome extension 商店,搜尋並安裝 React Developer Tools。在 dev 環境下打開開發者工具就可以看到多了
使用 React Profiler
打開 devtool 下的 Profiler,點擊開始錄製的按鈕,就可以開始錄製。一但開始錄製後,它會自動記錄每次頁面渲染時的效能相關資訊。

正常操作你想要偵測的畫面操作,都操作完之後,點擊停止錄製,開發者工具就會顯示各種效能相關數據供你查看。

如何看 profiler 的數據
React 的兩種工作模式
- render phase: 決定該 component 是不是有需要重新渲染
- Determines what changes need to be made to e.g. the DOM.
- React calls render and then compares the result to the previous render
- commit phase: 如果有任何改變,React 會呼叫並執行 LifeCycle
- when React applies any changes. (In the case of React DOM, this is when React inserts, updates, and removes DOM nodes.) React also calls lifecycles like componentDidMount and componentDidUpdate during this phase
Profiler 將 perfomance 的資料用 commit 做分類。顯示在下圖紅匡處
每個柱狀圖都代表一個 commit,當下檢視的 commit 會是黑色,可以透過選取每個柱狀圖示來檢視不同的 commit 的 performance 資料。
越長的柱狀代表該 commit 花了較多的時間去 render。
篩選 commits
當錄製的時間很長,捕捉到的 commits 數量會很多,會比較難快速查看哪些 commit 花了較多的時間去 render。這個時候就可以用 filter 的功能,點擊齒輪,輸入想要查看大概超過多少時間 render 的 commits。
Flame chart
Flame chart 顯示單一 commit 下 app 的狀態。每個區塊代表一個 React component(e.g. App, Nav)。bar 的寬度代表每次 component render 所花費的時間,顏色代表該次 commit 中它花了多少時間。
Bar 的寬度代表 component 和他的 children 最近一次花了多少時間 render。如果該 component 在該次 commit 沒有重新 render,那上面顯示的時間就是前一次 render 所花費的時間。寬度愈寬代表花費得時間愈多。
花費的時間: 黃色 > 藍色 > 灰色(代表在這次 commit 完全沒有 render)
點擊每一個 component 的區塊,可以看到他跟他的 children render 的相關時間,右邊會顯示選擇的 component 在該次 commit 的 props 及 state 的狀態。透過在不同的 commit 間切換,可以觀察到 component 是什麼的改變觸發了 render。
Ranked chart
可以一目瞭然,該次 commit 每個 component 所花費的時間,由大至小的排列。
單一 component 的 render 時間包含了他的 children,所以愈高階層的 component 通常會花最久的時間 render
Component chart
透過 component chart 可以追蹤特定 component 在該次錄製中總共 render 了幾次及它花費的時間。
double-click 單一 component 或是點擊右邊的長條圖 icon 就可以進入 component chart。點擊 component chart 的任一條,就可以回到該次 commit 的 Flame chart。
Interactions
記錄在錄製期間的每次 interaction。綠色的點點代表和每次 interaction 相關的 commit。