【问题标题】:Optimization of If statement in a Loop循环中if语句的优化
【发布时间】:2014-01-05 01:24:50
【问题描述】:

我有以下代码在每帧执行 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 循环会减慢我的游戏速度。是因为有多个Ands吗?

任何帮助将不胜感激。

编辑 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: 我还尝试将所有 Ands 替换为 AndAlsos。这并没有带来任何性能优势。

【问题讨论】:

  • And 更改为AndAlso 会发生什么?
  • 同样的事情。游戏平均速度约为 8FPS。
  • X 和 Y 访问器是否在进行任何计算?还有 _vertices 是什么类型的容器?
  • 另一个想法:将_vertices(vertexIndex)_currentPosition.X 放入变量中,并在您的If 语句中使用这些变量。
  • @mrlucmorin 是的!谢谢,解决了! Mod 运算符的原因是在每 4 个顶点处进行渲染。我想我只能用另一种方式来做。如果您想要积分,请发布这是一个答案,我会将其设置为accepted 答案。

标签: vb.net loops optimization if-statement directx


【解决方案1】:

您的问题可能来自Mod 运算符的使用。如果您可以避免使用它,或者找到另一种获得结果的方法,它将使您的循环更快。

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-23
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多