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

查看:20
本文介绍了是什么让 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) (currying 意味着你只使用单个参数的函数来编写一个函数 - 如果你用第一个参数调用它,你会得到一个函数作为结果,你可以调用返回的带有第二个参数的函数).

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天全站免登陆