【问题标题】:What are the performance side effects of defining functions inside a recursive function vs outside in F#在递归函数内部定义函数与在 F# 外部定义函数的性能副作用是什么
【发布时间】:2011-12-16 17:46:41
【问题描述】:

如果您有一个依赖于其他函数的递归函数,那么实现它的首选方法是什么?

1) 递归函数外

let doSomething n = ...
let rec doSomethingElse x =
    match x with
    | yourDone -> ...
    | yourNotDone -> doSomethingElse (doSomething x)

2) 递归函数内部

let rec doSomethingElse x =
    let doSomething n = ...
    match x with
    | yourDone -> ...
    | yourNotDone -> doSomethingElse (doSomething x)

3) 将两者都封装在第三个函数中

let doSomethingElse x =
    let doSomething n = ...
    let innerDoSomethingElse =
        match x with
        | yourDone -> ...
        | yourNotDone -> innerDoSomethingElse (doSomething x)

4) 更好的东西?

【问题讨论】:

  • 为什么是近距离投票?这似乎是一个非常好的/合理的问题。

标签: recursion f# let


【解决方案1】:
module Test =

    let f x = 
      let add a b = a + b //inner function
      add x 1

    let f2 x =
      let add a = a + x //inner function with capture, i.e., closure
      add x

    let outerAdd a b = a + b

    let f3 x =
      outerAdd x 1

翻译为:

[CompilationMapping(SourceConstructFlags.Module)]
public static class Test {

    public static int f(int x) {
        FSharpFunc<int, FSharpFunc<int, int>> add = new add@4();
        return FSharpFunc<int, int>.InvokeFast<int>(add, x, 1);
    }

    public static int f2(int x) {
        FSharpFunc<int, int> add = new add@8-1(x);
        return add.Invoke(x);
    }

    public static int f3(int x) {
        return outerAdd(x, 1);
    }

    [CompilationArgumentCounts(new int[] { 1, 1 })]
    public static int outerAdd(int a, int b) {
        return (a + b);
    }

    [Serializable]
    internal class add@4 : OptimizedClosures.FSharpFunc<int, int, int> {
        internal add@4() { }

        public override int Invoke(int a, int b) {
            return (a + b);
        }
    }

    [Serializable]
    internal class add@8-1 : FSharpFunc<int, int> {
        public int x;

        internal add@8-1(int x) {
            this.x = x;
        }

        public override int Invoke(int a) {
            return (a + this.x);
        }
    }
}

内部函数的唯一额外成本是新建FSharpFunc 的实例——似乎可以忽略不计。

除非您对性能非常敏感,否则我会选择最有意义的范围,即尽可能窄的范围。

【讨论】:

  • 答案可能从你的 sn-ps 中推断出来,但你真的应该把它拼出来。
  • 见最后一句话。我没有时间对其进行基准测试,但我提到了唯一明显的区别。
  • 创建FSharpFunc 可能会在大量代码使用时损害性能,但在大多数情况下这无关紧要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 2020-08-15
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多