English 中文(简体)
F#简易型及结构比较
原标题:F# simple type and structural comparison
  • 时间:2011-05-24 12:56:11
  •  标签:
  • .net
  • f#

in this question Why is this F# code so slow?, it is discussed that structrual comparison makes the function let min3(a, b, c) = min a (min b c) slow; shouldn t the structrual comparision on simple type be as fast as the native one? I am confused because people talked about always using HashIdentity.Structural for dictionary in F# in FSharp runs my algorithm slower than Python. If I have a dictionary with simple type(int or string) as the key, do I get performance penalty for using HashIdentity.Structural?

最佳回答

一般来说,我不会担心比较的性能,因为对于典型的代码来说,比较不太可能成为性能瓶颈。如果您已经确定存在性能问题,并且分析显示比较是原因,那么您可以考虑如何最好地解决它。

如果您确实需要考虑比较的性能,那么您可能需要了解编译器是如何工作的。在您引用的第一个示例中,min3函数的类型为a*a*a->;a when a:comparison。此函数将被编译为一个.NET方法,该方法采用3个泛型类型的参数,在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;
}

GenericLessThanIntristic方法也是泛型的,其中必须有基于被比较的实际类型执行比较的逻辑。这可能需要一些类型测试和虚拟方法调用。这些操作并不是非常昂贵,但它们比直接比较两个整数值要慢得多。因此,如果比较在您的工作负载中占很大一部分,那么使用通用比较例程可能会对您的整体性能产生很大影响,而将min3函数专门化为只处理整数而不处理任何通用值可能会在性能上大获成功。

同样,如果您只是将整数存储为字典键,那么在键上使用内置的GetHashCode()Equals()实现(字典默认会这样做)将比使用结构比较更快。然而,这对你来说是否是一个重要的区别将取决于你正在编写的实际代码——正如我之前所说,关键比较占用算法运行时间的很大一部分是不寻常的。

问题回答

暂无回答




相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签