我在 Windows 10 上使用 Python 3.10.7 和 3.11.0 运行这个简单的循环。
import time
a = 'a'
start = time.time()
for _ in range(1000000):
a += 'a'
end = time.time()
print(a[:5], (end-start) * 1000)
Run Code Online (Sandbox Code Playgroud)
旧版本执行时间为 187ms,Python 3.11 需要大约 17000ms。3.10 是否意识到只需要 的前 5 个字符a,而 3.11 执行整个循环?我在 godbolt 上证实了这种性能差异。
setState返回从钩子获取的(已更改的)先前状态useState似乎不会改变状态。运行以下直接代码片段
function App(){
const [state, setState] = React.useState([{x: 0}])
function changeCount(){
setState(prevState => {
console.log('before', prevState[0])
const newState = [...prevState]
newState[0].x += 1 //the shallow copy newState could potentially change state
console.log('after', prevState[0])//here x gets bigger as expected
return prevState //instead of newState we return the changed prevState
})
}
//checking state shows that x remained 0
return <div className='square' onClick={changeCount}>{state[0].x}</div>
}
ReactDOM.render(<App/>, document.getElementById('root'))Run Code Online (Sandbox Code Playgroud)
.square{
width: 100px;
height: 100px;
background: orange;
}Run Code Online (Sandbox Code Playgroud)
<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 …Run Code Online (Sandbox Code Playgroud)javascript ×1
optimization ×1
performance ×1
python ×1
python-3.10 ×1
python-3.11 ×1
react-hooks ×1
reactjs ×1
state ×1