下面的代码在每帧执行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循环,框架将增加到大约400FPS。我不明白为什么这个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,这并没有带来任何性能上的好处。
发布于 2014-01-04 17:24:50
您的问题可能来自Mod操作符的使用。如果您可以避免使用它,或者找到另一种获得结果的方法,它将使您的循环更快。
干杯
https://stackoverflow.com/questions/20923599
复制相似问题