Although you agreed that probably the best answer, I would like to provide an alternative.
Please note that the standard disclaimer applies - optimization is not optimization unless you have profiled your code.
However, if you encounter poor performance related to branches, you can reduce or eliminate them. The fact that your code has one or more inequality comparisons is not an obstacle - you can reduce your cases to a set of direct equalities and, if necessary, use this to index the table, and not to branch at all.
void doSomething(int len) { static const char* str[] = { "%2d > 3\n", "%2d < 2\n", "%2d = 2\n", "%2d = 3\n" }; int m1 = (len-2)>>31; int m2 = (len-4)>>31; int r = (len & m2 & ~m1) + !!m1; printf(str[r],len); }
Please note that these codes make several assumptions that may not be implemented in practice, but since we make a wild assumption that this even requires optimization in the first place ...
Also, note that better optimization may be possible with more knowledge about the actual range and type of input parameter, and indeed, what actual actions need to be performed.
JasonD Dec 28 2018-12-12T00: 00Z
source share