[ACCEPTED]-C# / F# Performance comparison-performance

Accepted answer
Score: 60

Natural F# code (e.g. functional/immutable) is 48 slower than natural (imperative/mutable 47 object-oriented) C# code. However, this 46 kind of F# is much shorter than usual C# code. Obviously, there 45 is a trade-off.

On the other hand, you can, in 44 most cases, achieve performance of F# code 43 equal to performance of C# code. This will 42 usually require coding in imperative or 41 mutable object-oriented style, profile and 40 remove bottlenecks. You use that same tools 39 that you would otherwise use in C#: e.g. .Net 38 reflector and a profiler.

That having said, it 37 pays to be aware of some high-productivity 36 constructs in F# that decrease performance. In 35 my experience I have seen the following 34 cases:

  • references (vs. class instance variables), only 33 in code executed billions of times

  • F# comparison 32 (<=) vs. System.Collections.Generic.Comparer, for 31 example in binary search or sort

  • tail calls 30 -- only in certain cases that cannot be 29 optimized by the compiler or .Net runtime. As 28 noted in the comments, depends on the .Net 27 runtime.

  • F# sequences are twice slower than 26 LINQ. This is due to references and the 25 use of functions in F# library to implement 24 translation of seq<_>. This is easily 23 fixable, as you might replace the Seq module, by 22 one with same signatures that uses Linq, PLinq 21 or DryadLinq.

  • Tuples, F# tuple is a class 20 sorted on the heap. In some case, e.g. a 19 int*int tuple it might pay to use a struct.

  • Allocations, it's 18 worth remembering that a closure is a class, created 17 with the new operator, which remembers the 16 accessed variables. It might be worth to 15 "lift" the closure out, or replaced it with 14 a function that explicitly takes the accessed 13 variables as arguments.

  • Try using inline 12 to improve performance, especially for generic 11 code.

My experience is to code in F# first 10 and optimize only the parts that matter. In 9 certain cases, it might be easier to write 8 the slow functions in C# rather that to 7 try to tweak F#. However, from programmer 6 efficiency point of view makes sense to 5 start/prototype in F# then profile, disassemble 4 and optimize.

Bottom line is, your F# code 3 might end-up slower than C# because of program 2 design decisions, but ultimately efficiency 1 can be obtained.

Score: 11

Here are a few links on (or related to) this 9 topic:

What I seem to remember from another 8 post on Robert Pickering's blog (or was 7 it Scott Hanselman?) that in the end, because 6 both are sitting on the same framework, you 5 can get the same performance from both, but 4 you sometimes have to 'twist' the natural 3 expression of the language to do so. In 2 the example I recall, he had to twist F# to 1 get comparable performance with C#...

More Related questions