In the below code, is there a way to avoid the if statement?
s = 13; /*Total size*/
b = 5; /*Block size*/
x = 0;
b1 = b;
while(x < s)
{
if(x + b > s)
b1 = s-x;
SendData(x, b1); /*SendData(offset,length);*/
x += b1;
}
Thanks much!
You can use a conditional move or branchless integer select to assign b1 without an if-statement:
This is only a useful optimization on in-order processors, though. It won’t make any difference on a modern PC’s x86, which has a fast branch and a reorder unit. It might be useful on some embedded systems (like a Playstation), where pipeline latency matters more for performance than instruction count. I’ve used it to shave a few microseconds in tight loops.
In theory a compiler “should” be able to turn a ternary expression (
b = (a > 0 ? x : y)) into a conditional move, but I’ve never met one that did.Of course, in a larger sense everyone who says that this is a pointless optimization compared to the cost of
SendData()is correct. The difference between a cmov and a branch is about 4 nanoseconds, which is negligible compared to the cost of a network call. Spending your time fixing this branch which happens once per network call is like driving across town to save 1¢ on gasoline.