小编Mic*_*ael的帖子

Python 3.11 的优化比 3.10 差?

我在 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 上证实了这种性能差异。

python optimization performance python-3.10 python-3.11

22
推荐指数
1
解决办法
2279
查看次数

功能组件的 setState 中的 prevState 到底是什么?

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 state reactjs react-state-management react-hooks

3
推荐指数
1
解决办法
9247
查看次数