Branch prediction and AND statements

Unity discourages the use of if statements, as it messes up the branch predictor. I’ve found a workaround to have multiple checks without using an if statement, to convert

if(mapNodeResult.isCover != 1) selectDestination = false;
if(mapNodeResult.isWalkable != 1) selectDestination = false;
if(GridFilter.FilterByBinning(worldCoord, binSize, bins)) selectDestination = false;

into

selectDestination = selectDestination && mapNodeResult.isCover == 1;
            selectDestination = selectDestination && mapNodeResult.isWalkable == 1;
            selectDestination = selectDestination && GridFilter.FilterByBinning(worldCoord, binSize, bins);

.

However, this seems logically similar to an if-statement - there is an early exit for example if one of the earlier checks return false. Anyone with hardware knowledge can chip in and determine if the second block is more burst-friendly?

Check the Burst assembly output and see if it generates a branch or not in both cases. Also, not all branches are bad. You just don’t want to abuse them as they can make code non-vectorizable.

For branching you can use this advice from Unity:

  • Avoid branches. Use math.min, math.max, math.select instead.

https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/ECSSamples/Documentation/burst_optimization.md