我有以下代码,在每帧执行 100 000 次的循环内运行(这是一个游戏):
If (_vertices(vertexIndex).X > _currentPosition.X - 100) And (_vertices(vertexIndex).X < _currentPosition.X + 100) And (_vertices(vertexIndex).X Mod 4) And (_vertices(vertexIndex).Z Mod 4) Then
_grassPatches(i Mod 9).Render(_vertices(vertexIndex))
End If
使用此代码,我的游戏运行速度约为 8 FPS。如果我注释掉 Render
行,游戏会以 100 FPS 左右的速度运行,但是,如果我注释掉整个 If
循环,则帧速率会增加到 400 FPS 左右。我不明白为什么这个 If ... And ... And ... And ... then
循环会大大减慢我的游戏速度。是因为有多个And
吗?
如有任何帮助,我们将不胜感激。
编辑1: 这是我尝试提高性能的方法之一(还包括一些额外的代码来显示上下文):
Dim i As Integer = 0
Dim vertex As Vector3
Dim curPosX As Integer
For vertexIndex As Integer = _startIndex To _endIndex
vertex = _vertices(vertexIndex)
curPosX = _currentPosition.X
If (vertex.X > curPosX - 100) And (vertex.X < curPosX + 100) And (vertex.X Mod 4) And (vertex.Z Mod 4) Then
_grassPatches(i Mod 9).Render(_vertices(vertexIndex))
End If
i += 1
Next
编辑 2:我的问题可能是由于分支预测失败造成的吗? (Why is it faster to process a sorted array than an unsorted array?)
编辑3:我还尝试用AndAlso
替换所有And
。这并没有带来任何性能提升。
最佳答案
您的问题可能来自于使用 Mod
运算符。如果您可以避免使用它,或者找到另一种获得结果的方法,它将使您的循环更快。
干杯
关于vb.net - 循环中 If 语句的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20923599/