C# vs C++ Performance

in

First and foremost, the .NET intermediate language (CIL) binaries (see What is .NET? for an explanation) built from your source code are pre-optimized by the compiler as good as it can. CIL itself has been designed in a way that allows it to be converted into efficient machine code easily.

Secondly, the CIL to machine code compiler tries to perform any inexpensive optimization its developers could think of. Because a CIL compiler has more informations available about the code than a typical C++ compiler would, it can even do some optimizations that are normally too time-consuming for JIT compilers.

You might be surprised how close the resulting performance matches that of comparable machine code programs. If, however, that isn't enough for you, you can still build heavily optimized machine code binaries of your .NET programs. Read Compiling .NET to Machine Code for details in this.

Benchmarks

There have been a lot of heated debates about the performance of C++ vs. C#, but surprisingly, only a few actual benchmarks can be found.

The problem is that directly comparing the performance of C++ and C# is very difficult. Depending on the way you write your application, the same approach can yield very different results in these two languages. You are even likely to change the way you write programs once you get used to your new programming environment.

The performance you can expect in real-world programs will probably look similar to this diagram:

Estimated performance of C# in comparison to C++ and Java

Do not take this as an actual benchmark. It is only an educated guess!

The probably most important differences in the performance characteristics of C# and C++ are:

  • C# can handle large numbers of small heap-based objects much better than C++ due to the generational garbage collector. However, if the C++ developer invests the time to profile the application and write a hand-tailored memory pool, C++ will outperform C# again.
  • C++ is way ahead in terms of pure number crunching performance. Most of the time, it's hardly noticeable, unless you're writing your own video codec or are creating a custom physics engine in .NET.