gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:23:18 29 4
gpt4 key购买 nike

我有以下代码在循环中运行,该循环每帧执行10万次(这是游戏):

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:我也尝试用 And替换所有 AndAlso。这并没有带来任何性能优势。

最佳答案

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

干杯

关于vb.net - 循环中If语句的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20923599/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com