Should I implement my own IComparable for a struct in F# *just* for performance reasons?

55 Views Asked by At

For a trivial struct like

[<Struct>]
type MyId =
    val id: uint
    new(v: uint) = { id = v }

is it recommended to implmement IComparable even if the default behavior is suitable?

1

There are 1 best solutions below

0
Brian Berns On BEST ANSWER

This is an opinion question, but my answer is no. Here's what the F# compiler generates for your struct (decompiled back to C#):

    [CompilerGenerated]
    public sealed override int CompareTo(MyId obj)
    {
        IComparer genericComparer = LanguagePrimitives.GenericComparer;
        uint num = id@;
        uint num2 = obj.id@;
        if (num < num2)
        {
            return -1;
        }
        return (num > num2) ? 1 : 0;
    }

This looks reasonably efficient to me, although it could be simplified.

Link to full output.

Related Questions in F#