I'm writing some audio code where basically everything is a tiny loop. Branch prediction failures as I understand them is a big enough performance issue that I struggle to keep the code branch free. But there is only so far that can take me, which got me wondering about the different kinds of branching.
In c++, the conditional branch to fixed target:
int cond_fixed(bool p) {
if (p) return 10;
return 20;
}
And (if I understand this question correctly), the unconditional branch to variable target:
struct base {
virtual int foo() = 0;
};
struct a : public base {
int foo() { return 10; }
};
struct b : public base {
int foo() { return 20; }
};
int uncond_var(base* p) {
return p->foo();
}
Are there performance differences? It seems to me that if one of the two methods were obviously faster than the other, the compiler would simply transform the code to match.
For those cases where branch prediction is of very high importance, what details regarding performance are useful to know?
EDIT: The actual operation of x : 10 ? 20
is merely a place holder. The actual operation following the branch is at least complex enough that doing both is inefficient. Additionally, if I had enough information to sensibly use __builtin_expect
, branch prediction would be a non-issue in this case.
uncond_var
because it does not know the complete set of possible derived classes ofbase
. In general closed problems (finite number of possible inputs) are easier to solve than open ones. – Gamin