3
votes

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.

1
Note that this won't be about branch (mis)prediction...Oliver Charlesworth
@OliCharlesworth Could you explain please?David
So far as I'm aware, GCC's __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 Charlesworth
I don't believe any such thing exists for the Delphi compiler.Nick Hodges
Borland compilers suck at optimzation nowadays :( You have to write likely branch code after then and unlikely one after else (which in most cases is good code style anyways)OnTheFly

1 Answers

1
votes

There is nothing in the language or compiler that allows you to supply hints for branch prediction. And in any case, modern architectures would ignore those hints even if the compiler emitted object code that contained hints.