web performance 介绍

在说react之前,需要介绍一个 web performance。Performance 接口可以获取到当前页面中与性能相关的信息。它有一个功能是可获得精确到千分之一毫秒的时间。在react中用到 performance 的api有:

  • performance.mark :根据给出 name 值,在浏览器的性能输入缓冲区中创建一个相关的timestamp。
  • performance.clearMarks:将给定的 mark 从浏览器的性能输入缓冲区中移除。
  • performance.measure:在浏览器的指定 start mark 和 end mark 间的性能输入缓冲区中创建一个指定的 timestamp。
  • performance.clearMeasures:将给定的 measure 从浏览器的性能输入缓冲区中。
  • performance.now:返回一个表示从性能测量时刻开始经过的毫秒数 DOMHighResTimeStamp。

分阶段

react在进入某个阶段时会使用mark进行标记,在执行完这个阶段时会使用clearMarks进行移除。我们根据这个特性来简单划分react阶段。代码如下:

  1. class App extends Component {
  2. render() {
  3. return (<div id='appId'>Hello World!</div>);
  4. }
  5. }
  6. ReactDOM.render(<App />, document.getElementById('root'));

在react-dom的performance.mark 处打断点。可以捕捉到 app 经历 React Tree Reconciliation 和 Committing Changes 两个阶段,具体如图示:
react-phase.jpg
若将代码改为:

  1. ReactDOM.render(<div id='appId'>Hello World!</div>, document.getElementById('root'));

有React Tree Reconciliation 和 Committing Changes ,没有App[mount]。