Optimization in std.algorithm.max?

Jerry jlquinn at optonline.net
Fri Nov 25 21:10:14 PST 2011


Jesse Phillips <Jesse.K.Phillips at gmail.com> writes:

> There is a good possibility that I don't know anything, but is there something about doing two checks that goes faster?
>
>         static if (isIntegral!(T1) && isIntegral!(T2)
>                    && (mostNegative!(T1) < 0) != (mostNegative!(T2) < 0))
>             static if (mostNegative!(T1) < 0)
>                 immutable chooseB = b > a || a < 0;


In this case, T1 (a) is a signed value and b is unsigned.  To do the
comparison, D will implicitly convert the signed variable 'a' to
unsigned.  This will wrap around the negative values.  Therefore, using the
case of 32 bit ints as an example, if b = 1, and a = -1, the comparison
performed will be

          1 > 0xffffffff || -1 < 0

The first test fails, so the 2nd is required to succeed.

>             else
>                 immutable chooseB = b > a && b > 0;

In this case, a is the unsigned value and b is signed and cast to
unsigned byt the compiler.  With a = 1 and b = -1, the test becomes

         0xffffffff > 1 && -1 > 0

The 2nd test is required to make this fail.

>         else
>             immutable chooseB = b > a;
>
> What has me baffled is the second checks after b > a. Doesn't b > a always answer the question? The only thing I can think of is a check for negative being faster, so shouldn't they come before the b > a check?


Jerry Quinn


More information about the Digitalmars-d-learn mailing list