4

I was thinking about the speed difference of C++ to C# being mostly about C# compiling to byte-code that is taken in by the JIT compiler (is that correct?) and all the checks C# does.

I notice that it is possible to turn a lot of these functions off, both in the compile options, and possibly through using the unsafe keyword as unsafe code is not verifiable by the common language runtime.

Therefore if you were to write a simple console application in both languages, that flipped an imaginary coin an infinite number of times and displayed the results to the screen every 10,000 or so iterations, how much speed difference would there be? I chose this because it's a very simple program.

I'd like to test this but I don't know C++ or have the tools to compile it. This is my C# version though:

static void Main(string[] args)
{
    unsafe
    {
        Random rnd = new Random();
        int heads = 0, tails = 0;
        while (true)
        {
            if (rnd.NextDouble() > 0.5)
                heads++;
            else
                tails++;

            if ((heads + tails) % 1000000 == 0)
                Console.WriteLine("Heads: {0}  Tails:  {1}", heads, tails);
        }
    }
}

Is the difference enough to warrant deliberately compiling sections of code "unsafe" or into DLLs that do not have some of the compile options like overflow checking enabled? Or does it go the other way, where it would be beneficial to compile sections in C++? I'm sure interop speed comes into play too then.

To avoid subjectivity, I reiterate the specific parts of this question as:

  • Does C# have a performance boost from using unsafe code?
  • Do the compile options such as disabling overflow checking boost performance, and do they affect unsafe code?
  • Would the program above be faster in C++ or negligably different?
  • Is it worth compiling long intensive number-crunching tasks in a language such as C++ or using /unsafe for a bonus? Less subjectively, could I complete an intensive operation faster by doing this?
NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • 2
    this is a very bad example - you are testing only the performance of random number generator and Console.WriteLine. – Marek Apr 20 '10 at 12:04
  • 4
    The **only** way to get maximum performance is to write **good** code. Whether you write it in C# or C++ doesn't really matter. Neither language is defined with a rule that says "Oh, and it is forbidden to compile this code to be more efficient than X". Both C# and C++ compilers do everything they can to make the code you give them *as fast as possible*. But yes, in many common cases, C# can be just as fast as C++. Sometimes it might turn out faster code. Sometimes it doesn't. Worry less about language, and more about the code you're writing. – jalf Apr 20 '10 at 12:28
  • @jalf: Do you have an example that demonstrate a faster speed execution of a C# application vs C++ application? The way I see C# being as fast as C++ or almost as fast as C++ is if you only use simple data types... – Alerty Apr 21 '10 at 16:29
  • There are at least a half dozen questions here on SO by people who wrote the same program in both languages and simply **cannot understand** why their C# version is faster. There are many reasons why C# can be faster. Garbage collection is far more efficient on average than manual memory management. Getting rid of pointers and fixing up some holes in the type system pretty much eliminates aliasing which prevents a huge number of compiler optimizations in C++. C/C++ aren't actually very compiler-friendly languages. In many ways, they're painfully hard for the comiler to optimize. – jalf Apr 21 '10 at 16:47
  • This series of blog posts should give you an example though: http://blogs.msdn.com/ricom/archive/2005/05/10/performance-quiz-6-chinese-english-dictionary-reader.aspx – jalf Apr 21 '10 at 16:48
  • @jalf: Somehow I am not entirely convinced when I see a '#include "windows.h"' in the C++ example... Do you have an example that is not dependent on windows for C++? – Alerty Apr 22 '10 at 21:50
  • @Alerty: Why would that make a difference? You think the compiler goes into "inefficient mode" when you include windows.h? – jalf Apr 22 '10 at 22:14
  • @jalf: Who knows? Maybe it does! :P Seriously, the real reason is that I can't compile the example in Xcode with gcc... I am on a Mac right now. – Alerty Apr 22 '10 at 22:40

2 Answers2

2

The example given is flawed because it does not show real life usage of both programming languages. Using simple datatypes to measure the speed of a language will not bring anything interesting. Instead, I suggest you create a template class in C++ and compare it with what is possible in C# for class generics. In the end, objects will bring some important results and you will see that C++ is faster than C#. Not to mention that you are comparing a lower level programming language with C#.

Does C# have a performance boost from using unsafe code?

Yes, it will have a boost but it is not suggested that you write only code with unsafe. Here is why: Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. In other words, unsafe code cannot be executed in an untrusted environment. For example, you cannot run unsafe code directly from the Internet. http://msdn.microsoft.com/en-us/library/aa288474(VS.71).aspx

Would the program above be faster in C++ or negligably different?

Yes the program would be slightly faster in C++. C++ is a lower programming language and even faster if you start using the algorithm library (random_shuffle comes to mind).

Is it worth compiling long intensive number-crunching tasks in a language such as C++ or using /unsafe for a bonus? Less subjectively, could I complete an intensive operation faster by doing this?

It depends on the project...

Alerty
  • 5,945
  • 7
  • 38
  • 62
1

Up to more than 100% of speed - depends a lot on the task, simply said.

More than 100% - yes, because the just in time compiler knows your processor, and I doubt you actually optimize for your hardware platform ;)

No SSE is a problem if you do matrix operations.

FOr some things with tons of arrays (image manipulation) The array tests kill you, but pointers work (i.e. unsafe code) as they bypass this.

Regarding things like overflow checking - be carefull. As in: in C++ you have the same possibly. If you need overflow checking, the performance issue is not there ;)

I personally would not bother with C++ in most cases. Partially yes, especially when you can benefit from SSE:

So, at the end a lot depends on the NATURE if your calculations.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • -1..C++ does not have to deal with garbage collection. C# does more things in the background then c++. You can do more optimization with c++. C# is a higher level language and therefore slower. – Luke101 May 05 '10 at 00:09