首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环中If语句的优化

循环中If语句的优化
EN

Stack Overflow用户
提问于 2014-01-04 16:34:07
回答 1查看 210关注 0票数 2

下面的代码在每帧执行100 000次的循环中运行(这是一个游戏):

代码语言:javascript
复制
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:是我试图提高性能的方法之一(还包括一些显示上下文的额外代码):

代码语言:javascript
复制
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,这并没有带来任何性能上的好处。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-04 17:24:50

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

干杯

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20923599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档