是什么让 FSharpFunc<>比 Func 更快? [英] What makes FSharpFunc<> faster than Func<>?

查看:25
本文介绍了是什么让 FSharpFunc<>比 Func 更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 FSharpFunc<> 的性能增强感到好奇.是否因为它不包含多个委托,因此在触发函数调用时不需要循环遍历所有引用?还有什么?

I'm curious about the performance enhancements that have been made for FSharpFunc<>. Is it the fact that it does not contain multiple delegate so there is no need to loop over all the references when firing a function call ? Anything else ?

推荐答案

我认为使用 FSharpFunc<> 而不是 Func<> 的主要动机是任何其他委托是您不能创建将从委托类型继承的类(起初,这听起来很合理,但在 .NET 中,委托实际上只是一些特殊的类,因此原则上可能允许这样做).为什么需要这个?

I think that the primary motivation for using FSharpFunc<> rather than Func<> or any other delegate is that you cannot create a class that would inherit from a delegate type (at first, this sounds reasonable, but in .NET, delegate is actually just some special class, so it may be in principle possible to allow this). Why is this needed?

如果您在 F# 中编写函数,那么它(在相对较少但非常重要的情况下)会以柯里化形式处理.例如 int ->内部 ->int 实际上是一个函数类型 int ->(int -> int) (柯里化意味着您仅使用单参数函数编写函数 - 如果您使用第一个参数调用它,您将获得一个函数作为结果,您可以调用返回的函数与第二个参数).

If you write a function in F# then it is (in a relatively few, but quite important cases) treated in a curried form. For example int -> int -> int is actually a function type int -> (int -> int) (currying means that you write a function using just functions of single parameter - if you call it with the first argument, you'll get a function as a result and you can invoke the returned function with the second argument).

如果 F# 使用委托,则类型将类似于 Func>.正如 Brian 所提到的,调用 f x y 将被翻译成两个调用:f(x)(y).然而,这种调用是最常见的(仅指定一个参数称为部分函数应用).因此,当 F# 编译这样的函数时,它会创建一个具有优化调用方法的继承类,以便它可以作为 f.Invoke(x, y) 调用:

If F# used delegates, the type would be something like Func<int, Func<int, int>>. As Brian mentioned, the invocation f x y would be translated into two invocations: f(x)(y). This kind of invocation is however the most common (specifying just a single argument is called partial function application). So, when F# compiles a function like this, it creates an inherited class with an optimized invoke method, so that it can be invoked as f.Invoke(x, y):

class @some_F#_name@ : Func<int, Func<int, int>> {
   public int Invoke(int arg1, int arg2) { /* optimized call */ }
}

不幸的是,不能通过继承标准的Func来创建这样的类(因为它是一个委托),所以F#必须声明它自己的可以用作基类的类型...

Unfortunately, it isn't possible to create such class by inheriting from standard Func (because it is a delegate), so F# has to declare its own type which can be used as a base class...

这篇关于是什么让 FSharpFunc&lt;&gt;比 Func 更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆