Will the second code be faster than the first ?

Can putting “if” statements inside a loop actually lowers the number of computations and speed up the program, or does it instead makes the program slower since now the program is going through one more step of checking?

Will this collision checking code be slower :-


void Player::checkCollision(vector<sf::FloatRect> blocks)
{
     //checking if player is on top of a block
    for(unsigned int i=0; i<blocks.size(); i++)
    {
        sf::FloatRect r = blocks[i];
        if(r.contains(point[9]) || r.contains(point[10]) || r.contains(point[11]))
        {
            colDown = true;
            break;
            }
        colDown = false;
    }
 }


then this collision checking code? :-


void Player::checkCollision(vector<sf::FloatRect> blocks)
{
	 //checking if player is on top of a block
	for(unsigned int i=0; i<blocks.size(); i++)
	{
					  
		if(blocks[i].getX()>0 && blocks[i].getX()<screenWidth)
		{
			sf::FloatRect r = blocks[i];
			if(r.contains(point[9]) || r.contains(point[10]) || r.contains(point[11]))
			{
				colDown = true;
				break;
			}
			colDown = false;
		}
	}
}

Dunno. Measure it.

^ Come on man, take a punt :stuck_out_tongue:

I will bet $1 the second one is faster!

Eliminating irrelevant processing for stuff off screen at the price of a couple of comparisons has to be good. Maybe this could be even faster if the player object had a bounding rectangle encompassing all its points, then one could replace the screen width check with a player width check…?

While the second snippet is 99% likely to be faster in the way the OP is using it (making some assumptions), the point is it won’t necessarily be in general. You really only truly when you measure it, under the same conditions that you expect the method to be used.

For example, what if the conditions for the block in screen check were never, or rarely, false? It’s be a redundant conditional.

Or even in more extreme cases:

  • Branches can be expensive if mis-predicted. Perhaps that cost could be greater than what is saved.
  • Maybe the compiler would no longer do certain optimizations as well. Or it may be the difference between inlining and not inlining.
  • Maybe the extra code causes more instruction cache misses.

Besides, it would appear as though the OP is killing the performance in far, far, worse ways than the differences in the code shown.

Secondly, learning how to measure your code is a much better habit than asking on a forum about what piece of code is faster. :stuck_out_tongue:

We can’t really tell you just by looking at the code you’ve provided. It’s going to depend on other stuff: how the contains method is implemented, how common it is for the rectangles to overlap vertically, etc. It might even depend on what you’re doing in other threads or what system you’re on.

The only way to answer this question is by profiling and measuring yourself.