Search code examples
f#icomparable

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


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?


Solution

  • 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.