Hacker News new | ask | show | jobs
by StilesCrisis 33 days ago
Only if you can actually prove that it matters. If you're always going to the same place, the branch predictor can quickly figure that out even if the compiler can't.
2 comments

Branch prediction is not magic and code that relies on it for branches that could otherwise be deduced statically can quickly result in destructive aliasing which results in branch mispredictions even on highly predictable branches.
> Only if you can actually prove that it matters.

That advice is often given, but I think few C++ programmers follow that to the letter, because you often know beforehand where your performance bottleneck is, and using some simple heuristics upfront may mean you won’t have to spend time benchmarking and refactoring later.

> If you're always going to the same place, the branch predictor can quickly figure that out even if the compiler can't.

But if the compiler knows which function is called, it can choose to inline it, can’t it? For short functions such as getters and setters, the difference can be huge. “call, move, return” instead of “move” is (ballpark) a factor of three, even ignoring cache pressure. The compiler may even choose not to construct a class instance at all, and keep its state in registers.