In terms of performance: C v.s. C++?

Intel17

Newcomer
Hello,

I was wondering if you guys could tell me which language, C or C++, is the fastest and by how much?

Thanks,

Intel17
 
If you write a program that can be compiled as both C and C++ (such an intersection would mostly just amount to C with slightly stricter type-checking), you should get basically the exact same performance in both languages. C++ comes with a heavier runtime, which may (very slightly) affect program startup time. On the other side, if you learn to use the STL properly under C++, the functions it offers are usually much faster (but also much more bloated) than its C counterparts - the standard example being std::sort being 3-10x faster than qsort() - and it will also help you avoid reinventing the square wheel whenever you need any of the standard data structures (lists, sets, maps, expandable arrays, etc). You should also be aware that C++ generally offers a somewhat higher abstraction level than C, which means that there are usually a larger number of ways to inadvertently write inefficient code in C++ than C (this is especially true if you start abusing operator overloading)
 
Last edited by a moderator:
This sort of question is going to bring out lots of fun arguments.

From my perspective, a programmer needs to worry about speed in two ways. One is how long it takes to write, and the other is how long it takes to run. As it was already pointed out, the C++ standard library offers many things that can help you write code faster, in addition to offering some benefits over the typical way of doing things in C. On the other hand, you could have spent hours hand coding exactly what C++ gave you and beat it marginally if you are really good and somewhat lucky.

I will object to the comment about operator overloading above. There is nothing inherently inefficient with it. As noted, you can write bad code with it, but you could do it just as badly with traditional functions.

I would like to mention some things that do make C++ slower, but these can be avoided. The first are exceptions. They seem like a great idea for some things, but they can have a real cost on function calls. Because of this, many compilers have the option to disable exception handling. The other big one I can think of is virtual function calls, these aren't death, as doing the same thing in C is about as expensive. The painful thing is that some people advocate over-virtualizing things. This leads to unnecessary overhead.

I personally prefer C++ because of things like STL and the additional abstractions it allows me to use when they make sense.

-Evan
 
Ken2012 said:
Where does C# fit in to this equation? Advantages/disadvantages/educated preferences...

Thanks.
C# as used in .Net relies on a JIT compiler, somewhat like Java. However, unlike Java, the language and the bytecode are designed from the ground up to avoid performance bottlenecks, so it appears to suffer less from startup slowness and UI response time problems than Java (C# appears to be fairly close to C/C++ in that regard). Once the program is up and running, all of these languages should have more or less similar performance (if you measure by throughput only), barring problems with their standard libraries and availability/misuse of language features.

C/C++ compilers seem to have come farther in implementing Auto-Vectorization than the C#/Java JITs, though - this particular feature tends to give rather conspicuous performance boosts on the occasions where it is actually used.
 
re runtime speed, the posts so far in this thread sortof create the impression (i'm sure quite unintentionally) that the best c++ can do is be as fast as c. let me just say that templates in c++ actually make the latter a far more semantically efficient language from which a decent compiler can produce faster code that same-level-of-decency c compilers usually do (at least for code not entirely relying on preprocessor expansions).
 
darkblu said:
re runtime speed, the posts so far in this thread sortof create the impression (i'm sure quite unintentionally) that the best c++ can do is be as fast as c. let me just say that templates in c++ actually make the latter a far more semantically efficient language from which a decent compiler can produce faster code that same-level-of-decency c compilers usually do (at least for code not entirely relying on preprocessor expansions).
Umm, how than this be the case? If I were to hand-expand a template instantiation into non-templated C code, the compiler should have exactly the same optimization problem in front of it as the template-based code would give, with the same kind of datatype and dependency information too.

While C++ templates are a much better code-reuse approach than the copy-pasting and preprocessor hackery you might end up doing in C, I don't see why they should give innately higher performance - or lower, for that matter.
 
Neither C++ or C is faster than the other, it all depends on the skills, availaible time, and ambitions of the programmer.

That should mark an end to this instance of this eternal discussion :)
 
arjan de lumens said:
Umm, how than this be the case? If I were to hand-expand a template instantiation into non-templated C code, the compiler should have exactly the same optimization problem in front of it as the template-based code would give, with the same kind of datatype and dependency information too.

though what you say is theoretically true, hand-expanding a template can be a very mundane job. to the point where it's not viable. hence regular c code does not employ such techniques. pretty much the same way humans don't write multi-thousand-lines of assembly code if they have a choice. but theoretically yes, they could. just that nobody wants to ('take this heavily templetized C++ code and translate it into equally-effective C, will ya? - erm, no, thanks')

[ed.] ok, to clarify this a bit as after re-reading my original post i realize it does not convey my original point clearly. template (AKA meta-) programming is a tool which allows the compiler to generate decent code without the need for the programmer to go to extremes. templates in c++ provide this, and the only thing that c has to offer at a comperative development cost is the preprocessor. why the latter is not as good is a whole different topic of its own.
 
Last edited by a moderator:
Since my natural tendency is to do things procedurally and derive algorithms on my own without researching in advance, "inventing the square wheel" is definitely a problem I have sufferend and one I constantly try to avoid. Very important point, arjan, although I didn't know there was a formal term for the disease. Seems to meld with T.S. Eliot's philosophy of maintaining a "historical sense" in works of poetry and art in general; I believe it applies to the development of most works of creativity.
 
Last edited by a moderator:
arjan de lumens said:
On the other side, if you learn to use the STL properly under C++, the functions it offers are usually much faster (but also much more bloated) than its C counterparts - the standard example being std::sort being 3-10x faster than qsort() -

I have recently discussed this issue with a co-worker. His fear was that string routines in C were potentially faster than C++ STL string routines (e.g. strcat(...) vs. string operator "+"). Although I did not perform timing tests, I feel that the "rate-determining step" in this particular program is not the string routines, and I would rather trade a bit of speed for readability, maintainability, and reliability (it's nice to leave behind archaic practices such as ensuring strings are null-terminated, determining the lengths of strings in order to allocate an output buffer of sufficient length for a concatenation operation, etc. every time a string needs to be managed).

arjan de lumens said:
You should also be aware that C++ generally offers a somewhat higher abstraction level than C, which means that there are usually a larger number of ways to inadvertently write inefficient code in C++ than C (this is especially true if you start abusing operator overloading)

Personally, I think the available higher level of abstraction is worth the potential performance detriment. Quite often, as somebody else mentioned, implementation algorithms are bigger peformance culprits than the implementation language.
 
The main thing you have to careful about in C++ is understanding what's going on underneath the covers. Unless you're careful, you can cause the compiler to do a lot of extra work that will hurt your performance without you even knowing.

Ex:

std::map< std::wstring, std::wstring > map1;
map1.insert( map1::value_type(L"aa", L"bb") );

How many temporaries did your compiler just create?
How many times did it copy the strings?
Did you just cause a heap allocation? How many?
How much stack did you just use?

Ex:

a = b + c;

What is the largest # of function calls that this line of code could potentially cause?

Etc.
 
Last edited by a moderator:
Intel17 said:
So from what I've gathered, C is the lower level of the two languages?

The original C++ compilers were just preprocessors to add Object Oriented type contructs.

These days C++ isn't achieved through preprocessing, but it's still just a set of extensions to the basic C language.

Pretty much anything you write in a C compiler will compile and run identically in C++.

C has a lot less tools available to hang yourself with.
 
if you ask out of interest, then yes I guess C is 'faster' than C++.

However, in practical terms, it's the algorithms you use, the data structures and the way you deal with them (page fault!) that have by far the most significant performance impact on your program.

I personally feel that unless you can achieve 2x the performance, you should do an optimisation, and thats assuming you are optimising in the first place. Often times performance problems will simply come down to whats already been mentioned, unintentional overuse of allocation, function calls, etc. Not really a language issue.

As for C#, in .net 1.1 the performance was within approximatly 10% of compiled C++ (using VS2003 compiler) with the exception of floating point which I believe ran in double precision by default (not 100% sure) - although I'm quite sure this has been fixed in 2.0 (and no doubt has other performance enhancements).


The real question is what language has most *potential* performance. In this case, it's actually the managed languages such as .net and to a lesser extent java that will (with time) provide the best performance. For example most native compiled apps may not take advantage of SSE1-3, 3dNow, MMX etc, yet a JIT compiled app can do so (or future tech). I've already had apps I've ported run faster in C# than C++ (although not always of course).
 
Premature optimization is mostly an evil rather than foresight. Often you don't quite know what will be the bottleneck because a processor is a VERY complex thing these days that runs off on their own and do things that achieve the same result as you asked for but not in the way your code specified.(it will do things out of order; prefetch things it thinks you will need instead of getting them when you ask; use different registers than you actually asked for and so on).

The most important thing is bugfree, readable code that is put into black boxes with proper interfaces so that it is difficult to misuse or misunderstand your code. Do performance profiling and fine tune the heck out of the bottlenecks if you need to.
 
soylent said:
The most important thing is bugfree, readable code that is put into black boxes with proper interfaces so that it is difficult to misuse or misunderstand your code. Do performance profiling and fine tune the heck out of the bottlenecks if you need to.

amen.
 
Back
Top