vb.net - 循环中 If 语句的优化

标签 vb.net loops optimization if-statement directx

我有以下代码,在每帧执行 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/

相关文章:

xml - 如何从 json 文件(或 xml 文件)创建 vb.net 对象类

vb.net - 使用 VB.Net 的 NerdDinner 验证问题

javascript - 如何循环遍历对象数组中的数组

c++ - 为什么这个 while 循环不退出?

javascript - Threejs - 使用缓冲区几何图形可以获得多少 yield ?

c# - EXE的大小会影响执行速度吗?

vb.net - 如何忽略vb.net中的服务器错误?在C#中,您只需尝试/捕获并忽略然后异常

java - 如何从扫描仪获取多个整数输入并将每个整数存储在单独的数组中?

javascript - 在 Javascript 中使用微小的变量名有多重要?

java - Android 中的 Activity 缓慢且无响应