F # simple type and structural comparison

in this question Why is this F # code so slow? It is discussed that structural comparison makes function let min3(a, b, c) = min a (min b c) slow; should a simple type of structural comparison be as fast as a native? I am confused because people talked about always using HashIdentity.Structuralfor dictionary in F # in FSharp runs my algorithm slower than Python . If I have a dictionary with a simple type (int or string) as a key, can I get a performance penalty when using HashIdentity.Structural?

+3
source share
1 answer

Generally speaking, I would not worry about comparison performance because typical code comparisons are unlikely to be a performance bottleneck. If you determine that you have a performance problem and the profiling shows that the reason is the comparison, then you might think about how best to solve it.

If you need to consider the performance of comparisons, you may need to understand how the compiler works. In the first example you specified, the function min3is of type 'a * 'a * 'a -> 'a when 'a : comparison. This function will be compiled into a .NET method with three arguments of a general type, which will look something like this in C #:

using LP = Microsoft.FSharp.Core.LanguagePrimitives;

T min3<T>(T a, T b, T c) {
    T d = LP.HashCompare.GenericLessThanIntrinsic(b,c) ? b : c;
    return LP.HashCompare.GenericLessThanIntrinsic(d,a) ? d : a;
}

GenericLessThanIntrinsic , , . . , , . , , , min3 , , .

, , GetHashCode() Equals() ( ) , . , , , , - , .

+3

All Articles