Is there any portable way of doing branch prediction hints? Consider the following example:
if (unlikely_condition) {
/* ..A.. */
} else {
/* ..B.. */
}
Is this any different than doing:
if (!unlikely_condition) {
/* ..B.. */
} else {
/* ..A.. */
}
Or is the only way to use compiler specific hints? (e.g. __builtin_expect on GCC)
Will compilers treat the if
conditions any differently based on the ordering of the conditions?
if
? Likeif([[unlikely]] unlikely_condition) { ... }
? Currently the syntax does not allow it. It does however allowif([[unlikely]] bool b = ...) { }
. Maybe one could abuse that :) – Vetterif(likely(...))
junk in completely non-performance-critical code, and IMO this is really bad. For one thing, it doesn't read naturally in English - it sounds like "if this condition is likely to be true" instead of "if this condition is true, which it likely is". And for another, it's just clutter. Unless you have lots of performance-critical conditionals that won't compile tocmov
or similar already, just ignore branch prediction hinting. – Pyosisif(unlikely(...))
. They prefer early exits that make code flow easier to follow. If they did not do this then the static branch prediction would always fail. – Ostentation