This is a common question for other compilers (C#, VC++, GCC.) I would like to know the same thing for the Delphi compiler (any version; I'm currently using 2010 and XE2 and will use XE4 soon.)
I have a situation in high-performance code I'm writing where a condition has to be checked, but in most cases no action needs to be taken:
if UnlikelyCondition then
HandleUnlikelyCondition
else
HandleLikelyCondition
end;
Often nothing needs to be done for the likely case:
if UnlikelyCondition then
HandleUnlikelyCondition
else
Exit
end;
I would like to hint to the compiler that the second branch of the if
statement is the one to optimize for. How can I do this in Delphi?
Current code
Currently, I have written my code assuming that the if
statement's condition equalling true is the best thing to optimise for:
if LikelyCondition then
HandleLikelyCondition
else
HandleUnlikelyCondition
end;
or
if LikelyCondition then Exit;
HandleUnlikelyCondition;
In a test just now using the first of these two examples, I get a 50% extra performance boost restructuring my if
statements like this, ie assuming the if
statement's condition is true
. Perhaps another way of phrasing the question is, is this the best I can do?
If you have not encountered branch misprediction before, this epic answer is an illuminating read.
__builtin_expect
(and similar) don't directly control the branch predictor (I'm not sure that's possible on modern x86), they just alter the generated code in favour of the "likely" path, such that it requires fewer instructions. – Oliver Charlesworththen
and unlikely one afterelse
(which in most cases is good code style anyways) – OnTheFly