Roy Osherove

View Original

Managed C++ performence vs. native C++

The user group meeting today went great. Very interesting stuff.

We actually got to see all the stuff that the .Net framework installation installs on the target machine. Lot’s of goodies in there right out of the box.

One of the things that interested me the most of a discussion about Managed C++ and how it compares to native C++ performance wise(It wasn’t the subject but it was still a C++ user group at the core so the discussion shifted several times). It was interesting to me because although I’m not a C++ developer (but I’ll have to be soon, yey!), I got into an argument with one of my colleagues. He claims(even though he has no real experience in .Net and he admits to only hearing it from other “certified” sources) that managed C++ will always be slower than native C++ because of several facts:

1)      The virtual machine gets in the way

2)      Security checks and others being performed before the code is actually executed.

 

In response I said that he’s talking nonsense, and that I know for a fact that Managed C++ can be much faster then native, and I had several points to that:

1)      JIT compilation before execution allows for optimized code to run against the current machine configuration and CPU(a Pentium 4,for example, has an optimized set of instructions for floating point operations I think).

2)      Um.. that was what I could come up with.

 

As a matter of fact, I stood there, without the ability to defend  what I believed to be true, because I had no real reinforcement in terms of optimizations. His arguments did make sense and I started to think that perhaps I was wrong?

Then to my rescue the subject came up at the user group and the speaker was damned straight about it – Managed C++ on average, can outperform the C++ optimizer on standard applications. The main reasons:

1)      JIT compilation – like what I said before

2)      Memory allocation. This was a point I had not considered.  The CLR allocates memory in a much different and faster way then the C++ memory allocation scheme. Basically in native C++ the memory allocation scheme had to look for a place in which to put memory chunks in(I won’t go into much detail here), when in the CLR the memory is always allocated without looking for free space. It just “puts” it on top (or at the end of) the memory chain and garbage collection later comes into play and removes any “holes” between chunks. This essentially is a much faster operation(not garbage collection, just memory allocation. GC is very expensive).

 

In the end, the CLR optimizations easily compensate for the other “slow” features.

So yeah, Managed C++ can be much faster then native. Cool!

 

Update: This post from Brad Adams helps clear things up even more!