C# vs C – Big performance difference

You must be comparing debug builds. I just compiled your C code, and got

Time elapsed: 0.000000

If you don’t enable optimizations, any benchmarking you do is completely worthless. (And if you do enable optimizations, the loop gets optimized away. So your benchmarking code is flawed too. You need to force it to run the loop, usually by summing up the result or similar, and printing it out at the end)

It seems that what you’re measuring is basically “which compiler inserts the most debugging overhead”. And turns out the answer is C. But that doesn’t tell us which program is fastest. Because when you want speed, you enable optimizations.

By the way, you’ll save yourself a lot of headaches in the long run if you abandon any notion of languages being “faster” than each others. C# no more has a speed than English does.

There are certain things in the C language that would be efficient even in a naive non-optimizing compiler, and there are others that relies heavily on a compiler to optimize everything away. And of course, the same goes for C# or any other language.

The execution speed is determined by:

  • the platform you’re running on (OS, hardware, other software running on the system)
  • the compiler
  • your source code

A good C# compiler will yield efficient code. A bad C compiler will generate slow code. What about a C compiler which generated C# code, which you could then run through a C# compiler? How fast would that run? Languages don’t have a speed. Your code does.

Leave a Comment