React.useMemo()
是否具有比较费用,就像shouldComponentUpdate()
中的React.PureComponent
一样?
将经常更改的变量放入useMemo()
或useCallback()
的部门很不好。
谢谢
答案 0 :(得分:1)
这里是一个微基准,React.memo()
似乎是最快的,PureComponent
位于中间,useCallback()
始终是最慢的:
class P extends React.PureComponent {
render() {
return <span onClick={() => this.props.n} />
}
}
function C(props) {
const c = React.useCallback(() => props.n, [props.n])
return <span onClick={c} />
}
const M = React.memo(props => <span onClick={() => props.n} />)
const target = document.getElementById('target')
function test(o) {
console.log('From fastest to slowest:')
const entries = Object.entries(o)
const results = new Map(entries.map(([name]) => [name, 0]))
for (let i = 0; i < 1e3; i++) {
for (let [name, X] of entries) {
const start = performance.now()
for (let j = 0; j < 1e2; j++) {
ReactDOM.render(<X n={i} />, target)
}
const took = performance.now() - start
results.set(name, results.get(name) + took)
}
}
const sorted = Array.from(results).sort(([, a], [, b]) => a-b)
for (let [name, t] of sorted) {
console.log(name, t)
}
}
test({PureComponent: P, useCallback: C, memo: M})
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id="target" hidden></div>