我一直在 React Native 中使用元胞自動機。我使用包含一行單元格視圖的物件陣列(下面的 CellRow 組件),并使用父組件中的 map 函式從該陣列回傳每個 CellRow。
const CellRow = (props) => {
const arr = props.arr
const yOffset = props.count
let mappedRow = arr.map((cell, index) => {
if ((index > arrayOffset - 1 && index < arraySize - arrayOffset) && cell === 1) { // OG expression
// if (cell && index < arraySize (-1 && arrayOffset) && index > -1 arrayOffset) {
return (
<View key={index} style={{ width: cellSize, height: cellSize, backgroundColor: "black", position: 'absolute', top: yOffset * cellSize, left: (index * cellSize) - (arrayOffset * cellSize) }} />
)
}
})
return (
<View >
{mappedRow}
</View>
)
}
這是一個螢屏截圖:

一切都按預期作業,所以我一直在清理我的代碼,并認為我應該嘗試簡化任何布爾運算式。我在 CellRow 組件中使用了 if 陳述句
if ((index > arrayOffset - 1 && index < arraySize - arrayOffset) && cell === 1)
把它放到一個布爾代數計算器中,它回傳了這個:
if (cell && index < arraySize (-1 && arrayOffset) && index > -1 arrayOffset)
新的表達方式似乎也同樣有效。但是,在生成單元格的幾頁之后,應用程式開始急劇變慢。當被映射的陣列為空時,即使在新頁面的開頭,行也會越來越慢。
I fixed this by switching back to my old expression, but am very confused why the new expression worked but performed much worse. Does react have some preference for the way boolean logic should be expressed?
uj5u.com熱心網友回復:
這個運算式不需要簡化,“計算器”給你的版本是錯誤的。
- 您的版本可讀、正確且已經簡化。
- 除非您每秒運行此測驗數百萬次,否則計算機的簡單數學運算速度非常快,因此這不是您的性能問題的原因。
- 您獲得的簡化版本沒有任何意義,并且可能會導致其他問題,例如超出范圍。
- 永遠不要相信一些隨機工具會為您生成優化的代碼。解釋器和引擎已經在這方面做得很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/419827.html
標籤:
