How to implement opCmp?

Honey via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 11 08:24:30 PDT 2017


On Friday, 9 June 2017 at 17:50:28 UTC, Honey wrote:
> Looking at the implementation of Tuple.opCmp, I'm not sure I'd 
> bet on existence of opCmp for fundamental types:
>
>         int opCmp(R)(R rhs)
>         if (areCompatibleTuples!(typeof(this), R, "<"))
>         {
>             foreach (i, Unused; Types)
>             {
>                 if (field[i] != rhs.field[i])
>                 {
>                     return field[i] < rhs.field[i] ? -1 : 1;
>                 }
>             }
>             return 0;
>         }

It turned out that there is a standard three way comparison 
function for ranges and strings [1].

Doesn't it make sense to introduce another overload of cmp 
similar to Steve's doCmp [2] right at that spot?

This would simplify the implementation of opCmp for aggregates 
and can also lead to a moderate performance benefit [3]. (Note 
that [3] does not provide an additional overload of cmp but uses 
a less elegant approach with the same performance 
characteristics.)

// $ ldc2 -O3 -release -boundscheck=off cmpTuple.d
//
// real	0m18.787s
// user	0m18.784s
// sys	0m0.003s
//
//
// $ ldc2 -O3 -release -boundscheck=off cmpTuple.d 
-d-version=singlePassCmp
// $ time ./cmpTuple
//
// real	0m16.109s
// user	0m16.102s
// sys	0m0.007s

[1] https://dlang.org/phobos/std_algorithm_comparison.html#cmp
[2] http://forum.dlang.org/post/ohedtb$1phe$1@digitalmars.com
[3] https://dpaste.dzfl.pl/7cbfa2e1965b


More information about the Digitalmars-d-learn mailing list