Hi there, this is more of a general c++ question, but figured someone on here might have the experience to advise me.
Right, so i have a 2d vector of int tile ids. The vector contains 4,225 ints. In my map editor, I originally used a nested for loop to check through them and change them if a mouse click collided with the space they represent. Here's an example:
bool foundTarg = false;
for (int i = 0; i < tileset.size(); i++)
{
for (int j = 0; j < tileset[i].size(); j++)
{
if (sf::FloatRect(i * 32, j * 32, 32, 32).contains(mouse))
{
tileset[i][j] = tileId;
foundTarg = true;
break;
}
}
if (foundTarg)
break;
}
However, I had the following idea, and that was that, at least when the click was deep into the array, that using modulo would save performance by cutting out the nested for loop. So here is an example of the function i used instead:
int x = static_cast<int>(pos.x);
int y = static_cast<int>(pos.y);
int remainderX = x % 32;
int remainderY = y % 32;
sf::Vector2f newPos((x - remainderX) / 32, (y - remainderY) / 32);
return newPos;
any thoughts on which would be more performant? Like I said, it seems obvious to me that the modulo method would be faster if the vector element was further in. But I'm sure its making my fps drop more than iterating through the vectors, which doesn't make sense to me.
Thanks for your time and patience ;)
Modulo would be faster because:
1) The nested loop can't be unrolled because the size of vectors are not static. So, there will be a jmp (jump) instruction for the loop.
2) 32 is power of 2 . considering that we have 2 optimizations:
For division:
x = y / 32 ;
is the same that:
x = y >> 5;
Bit shifting if faster than division, any good compiler will use bit shifting when possible.
And for the module ( % ) operand:
x = y % 32 ;
Could be optimized to:
x = ( y & ( 32-1) ) ;
Look at this snippet:
unsigned int getModulo(unsigned int n, unsigned int d)
{
return ( n & ( d-1 ) ) ;
}
// Where "n" is any unsigned int and "d" is a power of two number. ( In this case 32 )
Take into account that bit shifting only admit integers so, you'll only get integers.