[ ... ]
I have always heard that C++ compiles into machine code which is
close to optimal however C# is converted into p-code. So the speed
question could be, how does p-code compare to machine code.
That's not really the right question. A typical VM includes a "just
in time" compiler. This will dynamically convert (at least parts of)
the P-code to machine code for execution.
That means what you're comparing is (mostly) the optimization levels
provided by a couple of different compilers, and P-code is generally
used primarily as an intermediate language, at least for the
performance critical parts of the code. The P-code does have an
effect though -- an intermediate language that can't represent all
the concepts involved directly and easily can make it more difficult
to produce good output code.
There are theoretical arguments in favor of dynamic compilation, and
a few of them even work out in reality. For example, the virtual
machine can know the exact type of processor in use, and tailor the
code it generates specifically for that processor. When a developer
compiles C++, he generally won't know the exact type of processor in
the end-user's machine, so he can't select it as specifically.
Realistically, this only makes a substantial difference in a few
cases though. The most obvious (at least right now) is that you can
compile code that can run on either a 32-bit or a 64-bit virtual
machine. If the user has a 64-bit processor and a 64-bit VM
installed, they'll get better performance than if it was running as
32-bit code.
In the other direction, the end user is waiting while a JIT compiler
runs. As a result, the emphasis with (at least most) JIT compilers is
the compiler itself running fast, not that it produces the best
possible output code.
At least in my testing, C++ nearly always beats Java and .NET. The
margin varies from nearly nonexistent to quite large, but seems to
average around 25-30%. On the rare occasion that Java or .NET has
won, the margin has been much smaller, never exceeding 10%.
Other people have run tests with different results (there are a lot
of web sites devoted to proving that Java is faster than C++). So
far, those that have provided tests that were open to examination,
however, quickly showed that the C++ they were using was far from
optimal, in some cases in ways that seemed like they almost _had_ to
be intentional. Just for example, one I looked at years ago allocated
a block of memory with calloc, which zeros the memory, then
immediately used memset to zero the memory _again_ -- and then
overwrote that with other data, so there was no reason to zero it at
all. Of course, that's not the only example, but it is fairly
typical.
Conclusions:
1) It probably won't make a huge difference either way.
2) For pure speed, well written C++ still usually wins.
3) You should probably run some benchmarks yourself, not trust
anybody else's (even mine).