Performance Implications of Point-Free style

后端 未结 1 1250
悲&欢浪女
悲&欢浪女 2021-02-07 08:13

I’m taking my first baby-steps in learning functional programing using F# and I’ve just come across the Forward Pipe (|>) and Forward Composition (>>) operators. At first I thou

相关标签:
1条回答
  • 2021-02-07 08:34

    This answer is going to be F#-specific. I don't know how the internals of other functional languages work, and the fact that they don't compile to CIL could make a big difference.

    I can see three questions here:

    1. What are the performance implications of using |>?
    2. What are the performance implications of using >>?
    3. What is the performance difference between declaring a function with its arguments and without them?

    The answers (using examples from the question you linked to):

    1. Is there any difference between x |> sqr |> sum and sum (sqr x)?

      No, there isn't. The compiled CIL is exactly the same (here represented in C#):

      sum.Invoke(sqr.Invoke(x))
      

      (Invoke() is used, because sqr and sum are not CIL methods, they are FSharpFunc, but that's not relevant here.)

    2. Is there any difference between (sqr >> sum) x and sum (sqr x)?

      No, both samples compile to the same CIL as above.

    3. Is there any difference between let sumsqr = sqr >> sum and let sumsqr x = (sqr >> sum) x?

      Yes, the compiled code is different. If you specify the argument, sumsqr is compiled into a normal CLI method. But if you don't specify it, it's compiled as a property of type FSharpFunc with a backing field, whose Invoke() method contains the code.

      But the effect of all is that invoking the point-free version means loading one field (the FSharpFunc), which is not done if you specify the argument. But I think that shouldn't measurably affect performance, except in the most extreme circumstances.

    0 讨论(0)
提交回复
热议问题