2

I have the following code that runs inside a loop that is executed 100 000 times per frame (it is a game):

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

With this code my game runs at around 8 FPS. If I comment out the Render line, the game runs at around 100 FPS, however, if I comment out the whole If loop, the framerate increases to around 400 FPS. I don't understand why does this If ... And ... And ... And ... Then loop slows down my game so much. Is it because of the multiple Ands?

Any help would be appreciated.

EDIT 1: Here is one of the ways I tried to improve the performance (also includes some extra code to show context):

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

EDIT 2: could my problem be due to a Branch Prediction fail? (Why is it faster to process a sorted array than an unsorted array?)

EDIT 3: I also tried replacing all the Ands with AndAlsos. This didn't lead to any performance benefit.

Community
  • 1
  • 1
davidweitzenfeld
  • 1,021
  • 2
  • 15
  • 38

1 Answers1

3

Your problem probably comes from the use of the Mod operator. If you can avoid using it, or find another way of getting to your result, it will make your loop faster.

Cheers

Luc Morin
  • 5,302
  • 20
  • 39