Jump to content
Sign in to follow this  
HaSo4

System.Math.InRange implementation: Why with separate booleans?

Recommended Posts

Good day,

I found the implementation in the Math unit like this:
 

function InRange(const AValue, AMin, AMax: Integer): Boolean;
var
  A, B: Boolean;
begin
  A := (AValue >= AMin);
  B := (AValue <= AMax);
  Result := B and A;
end;

Why is that, shouldn't it be more performant as one-liner?

function InRange(const AValue, AMin, AMax: Integer): Boolean;
begin
  Result := (AValue >= AMin) and (AValue <= AMax);
end;

Maybe there is a catch, I don't see here.
The only reason to use two separate boolean, I can imagine, is for improving the debugging experience.

 

Share this post


Link to post

If the compiler optimization was worth a penny it would not matter which way the code was written and it would emit the best version regardless and depending on the situation where this function is being called and inlined - however, the compiler optimization is rather terrible so this might be some poor attempt to optimize for a certain situation where storing in two boolean variables creates less or no conditional jumps opposed to the short circuit evaluated combined expression with two comparisons.

  • Like 3

Share this post


Link to post

Thanks, a lot of information to read.
Yes, usually optimization should fix this, but since I know that Delphi is not perfect in that regard ...

I'll keep it as-is, since there seems no "back magic" behind.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×