Putting the fun in functional programming since 2005!
Friday, 4 May 2012
Efficiency of F# vs C#
F# provides some performance-related features that can make a difference.
Firstly, the implementation of delegates on .NET was quite inefficient and, consequently, F# uses its own FastFunc type for high-performance first-class functions.
Secondly, F# uses .NET metadata to convey inline functions so that they can be exported across APIs and, of course, that can dramatically improve performance in certain circumstances. Moreover, F#'s inlining allows functions passed as arguments to higher-order functions to be completely inlined and type specialized. Our F# for Numerics library makes extensive use of this feature to ensure that per-type functions such as comparison are specialized. We have seen this give performance in F# up to 2,350x faster than the equivalent C#. In fact, some of our numerical routines are consistently several times faster than vendor-tuned Fortran in libraries like the Intel MKL.
Finally, pattern matching can be extremely laborious to express in C# because the language lacks pattern matching and it is almost impossible to maintain optimized C# code equivalent to many non-trivial pattern matches. In contrast, the F# compiler aggressively optimizes pattern matches during compilation.
Conversely, the C# compiler may still be better at optimizing computations over value types (e.g. complex arithmetic) and has "goto" which can be more efficient than anything currently available in F#.