繁体   English   中英

React Native 项目使用简化的 boolean 表达式运行速度较慢

[英]React Native project runs slower using a simplified boolean expression

我一直在 React Native 中使用元胞自动机。 我使用包含一行单元格视图的对象数组(下面的 CellRow 组件),并使用父组件中的 map function 从该数组返回每个 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> ) }

这是一个屏幕截图: 显示规则 30

一切都按预期工作,所以我一直在清理我的代码,并认为我应该尝试简化任何 boolean 表达式。 我在 CellRow 组件中使用了 if 语句

if ((index > arrayOffset - 1 && index < arraySize - arrayOffset) && cell === 1)

将其放入 boolean 代数计算器,它返回:

if (cell && index < arraySize + (-1 && arrayOffset) && index > -1 + arrayOffset)

新的表达方式似乎也同样有效。 但是,在生成单元格的几页之后,应用程序开始急剧变慢。 当被映射的数组为空时,即使在新页面的开头,行也会越来越慢。

我通过切换回我的旧表达式来解决这个问题,但我很困惑为什么新表达式有效但表现更差。 react 是否对 boolean 逻辑的表达方式有一些偏好?

这个表达式不需要简化,“计算器”给你的版本是错误的。

  1. 您的版本可读、正确且已经简化。
  2. 除非您每秒运行此测试数百万次,否则计算机的简单数学运算速度非常快,因此这不是您的性能问题的原因。
  3. 您获得的简化版本没有任何意义,并且可能会导致其他问题,例如超出范围。
  4. 永远不要相信一些随机工具会为您生成优化的代码。 解释器和引擎已经在这方面做得很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM