这是我观察到的难以解释的性能问题的SSCCE。
我们有一个非常简单的React应用程序,其状态是单个计数器。 用户按下按钮增加计数器或按下另一个按钮以继续递增计数器。那就是它。
我们使用setState
衡量performance.now
的时间。
当从计时器调用时,结果setState
需要一个数量级的时间。
我的系统中手动点击案例的典型值:
cost was: 0.03999999999359716
cost was: 0.020000000004074536
cost was: 0.02500000000873115
连续增量案例的值:
cost was: 1.2200000000011642
cost was: 1.0449999999982538
cost was: 3.084999999991851
代码是:
const React = require('react');
var TimerMixin = require('react-timer-mixin');
const App = React.createClass({
mixins: [TimerMixin],
getInitialState: function() {
return { counter: 0, continuous: false };
}
, increment() {
const t0 = performance.now();
this.setState({counter: this.state.counter+1});
const t1 = performance.now();
console.log(`cost was: ${t1-t0}`);
}
, toggleContinuousIncrement() {
this.setState({continuous: !this.state.continuous}, ()=>{
if (this.state.continuous)
this.continuousIncrement();
});
}
, continuousIncrement: function() {
if (this.state.continuous) {
this.increment();
this.setTimeout(this.continuousIncrement, 30);
}
}
, render: function() {
const toggleContinuousIncrement = this.state.continuous
?"stop continuous increment"
:"start continuous increment";
return (
<div>
<div>
{this.state.counter}
</div>
<button onClick={this.increment}>increment counter</button>
<button onClick={this.toggleContinuousIncrement}>{toggleContinuousIncrement}</button>
</div>
);
}
});
export default App;