views:

2596

answers:

24

I've heard many opinions on this subject, but never saw any good proofs that C is faster than C++. So, ...is C faster than C++?

EDIT: This is a Runtime comparison.

+48  A: 

You can write slow code in any language.

JaredPar
This is true but it doesn't really help answer the question.
Robert Gamble
and you can write fast code in any language... except for java :)
m_oLogin
Assume you have infinite development time for a project. If you have more control of details in a language, it can be made to produce faster programs.
Brian R. Bondy
@Robert: it does answer the question. (hint: the question is wrong)
hasen j
@hansen j: I agree with Robert Gamble on this one. The question is not wrong. People are just interpreting it to mean something different than what he asked originally.
Brian R. Bondy
They both compile to native code, why would one be faster/slower? P.S. it's hasen, not hansen.
hasen j
I love how bashing Java in a comment gets 17 upvotes but if you did that as an answer it would be at least at -5.
Chris Lutz
@Chris: In my dream last night, comments could be down voted too. :o (I wish I was kidding.)
280Z28
@m_oLogin that's false, nowadays good written Java code can be on par with C and C++
fortran
@Chris/280Z28/fortran : understanding that comment required a sense of humour...
m_oLogin
@m_oLogin - And I have one. One of those 31 upvotes is mine.
Chris Lutz
m_oLogin: If you search the Intercal archives, there's something about an efficiently written Intercal program taking something like fifteen minutes to execute what any other language would do in seconds (or perhaps a fraction of a second). This being Intercal, the language designer considered that a feature.
David Thornley
It makes sense.... a joke makes a good comment, but a bad answer.
Jeremy Friesner
+16  A: 

we can compare only compilers and runtimes. comparing languages itself is useless.

and interesting link C++ and C code for the same problem: http://unthought.net/c++/c%5Fvs%5Fc++.html

where you can find: C++ Hash 34.697 sec. C Hash 35.929 sec.

Even lisp can be faster than C or have comparable performance

Trickster
You may have some languages which give you access to memory management, and some that don't. This may be a critical difference for some program's efficiency needs. comparing languages can be useful.
Brian R. Bondy
well, with C# you can directly use pointers. but because of GC (even parallel) you can't even predict performance in a large application
Trickster
+1 for pointing that the language itself doesn't have to do with the performance, but the compiler/runtime implementation.
fortran
You are right, this is an obvious point.However, there really is an interesting question here that is much more interesting on relying on the world of theoretical or imaginary compilers,which allow us to say with confidence that we cannot talk about the "speed" of programming languages. In reality, there is a finite amount of compilers that exist and there is some set of performance characteristics that the vast majority of them share.
BobbyShaftoe
Also, that link isn't very interesting. The speed difference is negligible but with 50% more code. As well, the original C++ ver is 18% the lines of C code but order of magnitude slower. Also, it is only 18% the lines of C code because it uses STL. The STL is much more code. As well, there are freely available C container libraries written in ANSI C.
BobbyShaftoe
+1  A: 

Languages don't have an ordering, and even implementations will be faster on some problems, slower on others, so your question is somewhat naive.

There exist C++ compilers that can emit better assembly for similar code than C compilers, thanks to much more type information in C++, but likely the C compilers will get lucky too, with a much simpler, older language. Go check the language benchmarks game.

Don Stewart
+7  A: 

Given compilers of identical good quality, and roughly identical source code, exactly the same binary code should be generated for both C and C++, so neither should be any faster than the other. Of course you can use low-quality compilers, or write code that will compile down to slower binary code (in either language, but C++ is a larger language, so it gives you more rope for you to shoot yourself in the foot with, if that's what you're after;-).

Appropriate use of generics in C++ may let you easily write reasonably compact code that runs extremely fast (see the Boost libraries for some examples); of course you could write equivalent code in C but (since preprocessor macros can't automatically specialize by type) it might have to be more verbose, perhaps extremely more verbose. (IOW, the compile-time processing that template expansion can do for you might have to be done manually if you were using a language without templates as powerful as C++'s).

Alex Martelli
+1 if I took about 20 years I could write a hyper-efficient Ruby compiler that would be as fast as (maybe faster than) C.
Chris Lutz
"Appropriate use of generics in C++" ... templates?
Joren
@Joren, yep, template metaprogramming (i.e., generics-based metaprogramming) is e.g. what some parts of Boost use to push certain computations to compile-time (yielding very fast-running code), for more cfr e.g. http://en.wikipedia.org/wiki/Template_metaprogramming .
Alex Martelli
I think the proper term is "generic programming" which can be done in C++ with templates. Regarding "the same binary code": what about exception handling? I'd think C++ has some exception handling overhead (mostly in terms of code size).
sellibitze
There isn't really a "generic METAprogramming", since generic programming need not supply a Turing-complete compile time sublanguage (e.g., I believe Java doesn't). If you have no dtors anywhere, nor exception-related construct, a good C++ compiler should impose no code size penalty wrt a good C compiler.
Alex Martelli
+44  A: 

Good question.

In general:

If you consider most programs, you won't see any difference now days.

Your bottlenecks can be discovered with profiling, and they will probably not be caused by any difference in features of C vs. C++.

Assuming you have infinite development time for a project. If you have more control of details in a language, it can be made to produce faster programs. The problem is that you never have infinite development time, and the time that you focus on details could be spent solving your true bottlenecks.

Where the "C is faster than C++" argument comes from:

With C you focus on more details than pure C++. For example if you add some string to an existing stl string, you won't be sure if you are allocating a buffer or not. With C you can be sure that you re-use exactly the old buffer.

Ditto with any STL container, most of your memory will be allocated on the heap, even know your object is created on the stack. With C you can be sure that you allocate your memory on the stack which is faster than the heap.

Another point is that of vtables with polymorphism. With C you won't have lookups for function calls in a vtable. They will be direct. A vtable function call is slower than a normal function call.

Of course compiler optimizations will optimize many things for you so both languages will be equivalent, but not the mentioned stuff above. Also, when I say C is faster than C++ it is by such a little amount that most programs won't care.

Comparing languages is useless?

Some posters have said that comparing languages is useless. I disagree.

Of course you can have some compilers of C++ emit more efficient code than others. But this does not discredit the fact that some languages are more focused on very low level details so that you can have optimal performance.

Different languages different goals:

Different languages have different goals. The C language is not focused for example on disallowing you to shoot yourself in the foot, but it is more focused on giving you control of most details.

The C# language on the other hand is more focused on not allowing you to shoot yourself in the foot. Remember I'm comparing languages not the actual runtime of C#.

C++ is somewhere in between (assuming you aren't dropping down to C). You can still shoot yourself in the foot, but you lose some control of what your program does exactly.

C++ being an almost superset of C:

C++ is almost a superset of C. Meaning that you can drop down to C at any time and do manual memory management instead of using something like an STL string.

Brian R. Bondy
about shooting yourself in the foot that is possible with all the languages. anyway good answer +1
Yassir
@Yassir: Ya it's not black and white, it's a spectrum :)
Brian R. Bondy
Understanding the inner workings and implications of using STL is no different to understand the inner workings and implications of using *any* library, in *any* language, standard or otherwise. I don't think that can be held against C++.
Stuart
The argument is more towards "more control => more speed potential" and not understanding of a more complicated 'thing'.
Brian R. Bondy
So how does "C++ is somewhere in between" account for, say, std::sort being *vastly* more efficient than C's qsort?
jalf
@jalf: Also I have no doubt that anyone here could produce an infinite number of counter examples on top of your one. See @JaredPar's answer for what I'm getting to.
Brian R. Bondy
The point about STL and heap memory is an odd one. If you're sane and you don't want to impose arbitrary limits on buffer sizes, you're going to use the heap, even in C. It's true that unenlightened C++ development encourages heap abuse, but disciplined use of the libraries has its advantages too. See also this paper by Stroustrup, which really sold me on STL, even though I'm mostly a C guy. http://www.research.att.com/~bs/hopl-almost-final.pdf
asveikau
Once you get past the whole "you can't compare the speed of languages" stuff that gets a lot of applause and you examine some more real world stuff, there are more performance issues than just "using the STL is slower" type stuff. Using compilers that actually exist (not the imaginary theoretical ones which allow us to say with confidence that we cannot talk about the "speed" of a programming language") then we see there are extra overheads in C++ binaries vs C binaries.
BobbyShaftoe
Added vtable / polymorphism example to supplement the heap management arguments.
Brian R. Bondy
@asveikau - No, C99 allows you to define arbitrary-sized arrays on the stack.
Chris Lutz
You should also mention that it's possible to write slower code in C than in higher level abstractions. For example it can be faster to use a garbage collector than to do it manually. Languages that use JIT can be remarkably faster because they are able to do runtime-optimization. Those two examples don't work for C versus C++, but there are similar things. A self-written algorithm that is included in the STL is almost always slower then the STL counterpart.
Georg
@Chris Lutz - OK, then what happens when the buffer I'm working with causes me to overflow my stack? Using stack "because it's faster" is not always the right idea, especially if the size is going to be unpredictable.
asveikau
I think the polymorphism remark is irrelevant here. Virtual functions calls are slower than non-virtual calls (albeit only 1 assembly instruction), but if you don't need your method to be virtual, just make it non-virtual. If it has to be virtual, then if you would write the code in C, you would probably have to use function-pointers, and thus you have the same overhead.For the rest, great answer. +1 from me.
Patrick
+8  A: 

The question does not make much sense. C is a subset of C++ (aside from a number of minute differences). Any C code is C++ code at the same time (again, aside from some irrelevant incompatibilities). For this reason C++ is exactly as fast as C and vice versa.

Most of the time when the question of comparative performance pops up, people are often insisting on using some "real C++ code" on the C++ side, which is normally some code that heavily uses C++-specific features. In 99.999% of the case the result is a completely and utterly meaningless comparison of apples to oranges done by people who don't even begin to understand what they are talking about.

Once again, there's exactly zero difference in performance between C and C++. Any alleged differences in their performance is just the result of meaningless experimenting done by people who don't understand well what C++ is and what it is intended to be.

I also would would like to add that in some practical experimens the same C code was known to exhibit different performance chracteristsics when compiled by C compiler and by C++ compiler (or by the same compiler in C mode and in C++ mode). However, so far anomalies like that have always been demonstrated to be purely Quality-of-Implementation (QoI) issues, meaning that the reduced C++ performance is a direct consequence of the lower quality of that specific C++ compiler.

A classic and rather well-known example would be the potential run-time overhead introduced by internal household code emitted for exception handling purposes, meaning that even pure C code in exception-aware environment might get compiled into a slower machine code by a C++ compiler. However, it has been demonstrated that a quality exception handling implementation can do all that with zero run-time overhead.

AndreyT
C++ is intended to be a mixture of low-level language and high-level abstractions, and how efficient it is depends on which part of the spectrum you end up on. If you stick to the low-level parts of the language, you're essentially writing C, not C++. Comparing C to C is, as you say, "a completely and utterly meaningless comparison."
Chris Lutz
What I'm saying is that in C++ you can use different-level constructs in order to obtain the desired performance from the resultant code. If you *need* the performance of raw low-level C code - there's nothing in C++ to stop you from getting it. If you don't need that kind of performance, you can use slower, but maybe more readable higher-level construct of C++. But evaluating the general speed of C++ code by bechmarking C++ code that didn't care and didn't need to be fast - that's what I call nonsense.
AndreyT
If we need the performance of assembly language we can drop down to that - does that make comparing C to assembly equally useless? If we need better performance we can write Perl/Python/Ruby modules in C - does that make comparing scripting languages to compiled languages useless?
Chris Lutz
Comparing C to assembly is not useless specifically because some inherent traits of C semantics make it virtually impossible to achieve assembly-like performance from C (at least in the real world with real world optimizers) regardless of how low-level our C code gets. So, assembly is objectively faster and there's no way around it. C++ semantics, on the other hand, is not objectievly restricting C++ code from achieving C-like performance. It is achievable in practice. Which is why claiming that C is faster doesn't make sense.
AndreyT
"C is a subset of C++" - to nitpick, no - C and C++ share a common subset ;)
Georg Fritzsche
You probably mean C99. And you are right. As for C89/90, saying that it is a "subset with a number of minute differences" is correct.
AndreyT
The answer and some comments seem to suggest that a higher abstractions and performance are mutually exclusive. This is not the case since we have templates.
sellibitze
@AndreyT: No he didn't mean C99. Even some C90 programs won't compile with a C++ compiler. Try using c++ keywords for variable names, etc.
sellibitze
@sellibitze: I have encyclopedic knowledge of each and every difference between C89/90 and C++98. Yet, what I said in my original answer was: C (implying C89/90) is a subset of C++, *some minute differences aside*. In the context of discussion about performance, the differences between C89/90 and C++89 are indeed minute.
AndreyT
Sorry, I just read the first half of your comment. I didn't miss the "some minute differences"-part in your original answer, though.
sellibitze
A: 

Let me (roughly) quote a joke from one of South Park episodes.

Teacher: Remember that there are transitive verbs, such as, "The boy threw the read ball", which on the futurespeak is, "Gwack, qu-kwo-quok, uk uk kwack". Also there are intransitive verbs, such as: "The 11:15 bus from Denver arrived twelve hours late." Or, in futurespeak, "Quack".

Since you're referring to the speed of languages, that's what you should measure: the effort you put into expressing a particular program. From that point of view C++ is much faster, sunce, due to it's OOP, templates and operator overloading, you can write same programs as in C with fewer keystrokes and unnecessary operators.

Of course sometimes same programs will be slower. But instead you gain development speed, which is crucial for large-scale projects.

Pavel Shved
+12  A: 

Actual empirical results are available at the language shootout for C vs C++.

Naturally, all benchmarks can be quibbled with, but language shootout is fairly rigorous in its use of multiple hardware platforms and languages.

Dirk Eddelbuettel
Props for rebutting this very silly question.
pst
Jason S
@Jason - that would depend on whether you compiled your doppleganger code with a c or c++ compiler. the c++ compiler might introduce some performance issue, in theory.
Peter Recore
+1  A: 

The short answer is, no, C is not faster than C++.

The long answer is, it depends on what you're doing, how familiar you are with either language, what compiler you're using, etc.

For example, if you don't know what you're doing with C++ you may end up writing very slow code, because you don't realize that something you're doing is causing a lot of temporary copies of objects to be created and destroyed. Additionally, since C++ offers higher level abstractions, performance is often a function of how well the compiler is able to cleverly "optimize away" the various levels of abstraction.

On the other hand, since C doesn't have generics it's often difficult to achieve the same sort of highly-efficient generic code that you can get with C++ templates, without sacrificing type safety or resorting to dangerous macros. (The qsort versus std::sort is the canonical example of this sort of thing.)

Charles Salvia
A: 

Some features of C++ insert a performance penalty in the code, which is not immediately obvious. For instance, a method call in C++ is as fast as a function call in C if this method is static. If not, at least you'll have an extra push to preserve the register that stores the this pointer before the call, and a pop after. If the method is also virtual, then you'll have a virtual table lookup, which may imply an internal function call. The same happens if you have exceptions and/or RTTI. With exceptions, you have extra code generated at the beginning and end of every method. With RTTI, you have internal function calls to check type hierarchy trees.

Notice that all these things happen "under the hood", so unless you're aware about how they work, you'd be unable to spot their performance effects. That's the main difference from C, in C an experienced programmer can predict with more precision the performance because there are much less factors to take into account.

That said, a C++ program with a good architecture probably won't suffer from performance due to these factors. In most cases the performance difference is not significant, and in those little places in which performance is critical, you can explicitly avoid them (or write that code in C or assembly). The benefit of using C++, especially in large projects where scope control is a major factor and you need things like classes and namespaces to deal with it, is far greater. And, in some cases, like the optimizations made possible by inlines combined with TMP, you'll actually gain performance.

A sidenote: this site has a good comparision of performance for similar programs in different computer languages:

http://shootout.alioth.debian.org/

The pages comparing C++ and C is:

http://shootout.alioth.debian.org/u32q/c.php

Fabio Ceconello
A: 

I believe both would be about equal because they both will produce byte code binaries.

The only slowness/increases in speed you would notice is whatever debugging code or "optimizations" each compiler will do.

You could probably write a program that does some intensive calculations and record the amount of time it took to do it.

Nathan Adams
What do you mean by "byte code binaries"? "Byte code" is usually used to mean an intermediate language, similar to machine language but not identical, and C and C++ compilers generally target the native machine code. Indeed, byte code usually results in slower performance. Not to mention that different languages have different runtime requirements, and different amounts of accessible information in the source code, so they will often compile differently. C and C++ are usually at least among the fastest.
David Thornley
When I refer to byte code, I am essentially talking about "machine code". Examine the wikipedia entry for "byte code" and you will see it is one instruction at a time, which, can we agree for simplicity that a single core processor can only execute a single instruction at a time? Of course I may not be totally correct in saying "byte code" is "machine code" but the ideologies are the same. "bytecodes are compact numeric codes, constants, and references (normally numeric addresses)" which, essentially, machine code is. Right or wrong?
Nathan Adams
A: 

Generally, hand-crafted code for a specific platform, by an expert in that platform, will be faster in C than in C++, because, very simply, C lets you think at a lower level, closer to the actual instructions that are executed.

However, the other side of the argument is that C++ is a higher-level language, allowing you to communicate with the compiler and standard library code in a more direct way. Since the compiler and standard libraries are more expert than most programmers, they are often better placed to implement fast code FOR you, than if you tried to do it yourself. This becomes especially true if you're talking about multiple platforms, or even different CPUs in the same family.

Of course, then there is the question of which is the faster language to learn well enough to use optimally. I'd argue that C++ is very complex for what it does. Personally, I loved C as a low-level language, but if I'm looking for something higher-level, I don't really consider C++ these days; I go straight to higher levels still, like python.

p.s.: if you want to research this further, look into Vala -- a relatively new language which is a lot like C#, but has performance better than C++, and much closer to C. It's implemented in C, and based on relatively modern object-oriented C programming techniques, so that should tell you something.

Lee B
With respect to the first paragraph, C++ contains as near-as-makes-no-difference all of C, so nothing in C++ prevents you from "thinking at a lower level"
Clifford
Well, I'm talking about the usual or even best practice associated with each language, of course. In C++, you're encouraged to use the STL including iterators, operator new, and so on. In C, on the other hand, you're encouraged to know the (albeit still slightly abstracted) memory layout of an array. This leads to very different code performance, and yes, a different level of coding.
Lee B
+1 for not considering C++ these days. I've been itching to post this link somewhere: http://yosefk.com/c++fqa/
James Morris
@James: The FQA is heavily biased and includes many "non-arguments" and misunderstandings. I would not recommend it. One could create a similar page that rips this FQA apart for what it's worth. Maybe this is not such a bad idea. Pointing out the flaws of this FQA again and again in discussions like this is wasting quite a lot of time.
sellibitze
+6  A: 

In C++ you pay only for what you use when compared with C.

So, assuming that you use a single toolchain with C and C++ compilation modes (almost invariably C++ tool-chains have a C compilation mode), if you compiled code using only the C subset but using C++ compilation, you will almost certainly see no difference between C and C++ (assuming identical optimisation level).

C++ has an additional run-time start-up step of invoking constructors for static objects, but if you have none (and you won't if the code uses only the C subset), that is insignificant.

Furthermore C++ has a number of features that C does not that have no impact upon run-time performance at all. For example function overloading, built-in bool type, default arguments are but a few that effectively come for free, mostly because they are merely 'syntactic sugar'.

Simple classes do not carry a significant cost, and none compared with equivalent "Object Based Programming" coding methods you might employ in C. More advanced class behaviour (full OOP rather than OBP), such as inheritance, polymorphism may carry some cost, but not much.

Some C++ features are sometimes more expensive than the code you might produce in C to perform the same function, but this often because additional functionality is provided. For example STL container classes, and std::string perform automatic memory management; this makes them easier to use as well as safer and more flexible, but if your container's capacity changes often, the memory management that occurs behind the scenes can make these look slower than simple arrays or C-strings. On the other hand, if you wrote data structures in C with the same functionality as STL, you'd do well to get as good performance.

The real performance hit in C++ occurs when you are not aware of the consequences of your own actions, and code in such a way for example that objects with heavy constructors/destructors go in-and-out of scope very frequently or are passed by value or copied unnecessarily.

In short, C++ is not intrinsically slower than C, but allows you to write code that has a higher cost. This cost may be through bad coding, or it may simply because you are taking advantage of features that make the code clearer, more maintainable, have fewer bugs, or faster to implement. Using C++ to enhance productivity and quality is often more important that some trivial or insignificant performance difference in the resulting product.

Clifford
+1 great answer! I missed the generic programming + inlining possibilities point, though.
sellibitze
A: 

Most of the time, raw performance is an academic rather than real-world metric.

When it matters, both languages allow for the same performance to be delivered.

When it matters a lot, programmers won't use either of them - assembler is the only way to wring every last drop of performance from the available hardware.

When it really matters, we replace the hardware - graphics cards are now used rather than software renderers running on general-purpose CPUs.

Jason Williams
+2  A: 

Since C++ builds on C, allows exactly the same style of programming, and tries to honor the "zero overhead principle", I'd be surprized if you couldn't write a C++ program which is at least as fast as its C counterpart. The toolbox (as in language features) of C++ is just a bigger. The C++ features you chose to avoid hardly affect performance in a negative way. I'm not sure about exception handling but if I remember correctly there are EH implementations out there with zero overhead in terms of execution speed.

One example where C++ really shines w.r.t. performance is std::sort in combination with function objects as comparator whose code is inlined. Of course, this extends to other generic template magic like expression templates which provide high abstractions and can compete with hand-crafted C code. C++ proves that high abstractions and performance are not mutually exclusive.

sellibitze
+2  A: 

No. C++ is almost a strict superset of the C language. Since similar optimizing compilers are available for both languages, algorithms written in C can generally be used as-is in a C++ application with the same performance. Therefore, in order to make C++ code perform like C, one simply writes the code the same way they would in C.

Yes. C++ is an extremely complex language. While an expert C++ developer is able to write expressive, type-safe, highly maintainable (to other experts) code, it is much more difficult to find a C++ expert that it is to find a C expert. This often leads to development teams containing members whose average knowledge results in code that does not take full advantage of C++'s strong points.

No. C++ templates are a Turing-complete compile-time language incorporated into C++. They can be used to perform many operations at compile time that would otherwise be performed at run time. Templates can also be used to write generic methods exhibiting excellent performance across a multitude of types, with additional benefits of type safety.

Yes. The semantic complexity of the C++ language results in an inevitable increase in its compile times. When moderate use of C++-specific features are combined with a source structure that doesn't account for constructs that slow down the compile process, incremental build times become so demanding that they severely restrict the overall productivity of the development team. Since tools don't currently exist for instrumenting the compiler to identify the source constructs responsible for high build times, there is no way to ensure that large projects will not meet this fate.

Neither. The best answer to this question is that developer experience matters more than language where application performance is concerned. In my experience, for any non-trivial program, profiling the application reveals that the leading performance problems are almost always due to poor choice of algorithm or application design and have nothing to do with the performance associated with the language in use.

280Z28
A: 

First scenario: They are the same. Because If you write exactly the same code, C++ will be about the same performance as C code. C++ has some optional features (like exception handling) that cause the C++ code to be a little slower (you can turn it off in most compilers).

Second scenario: C++ can be faster. C++ is a higher level language, and well written C++ code can be optimized better by the compiler. I have myself written an image compression library in C++ that beats the C implementation by 30-40%. But that was after doing C++ for 9 years.

Third scenario: C++ can be slower. The features that C++ add to C can slow down programs if the programmer is not aware of their costs if used inappropriately. Examples are excessive copying of structs, inappropriate use of virtual functions, exceptions, or templates. This is unfortunately quite common in complex C++ projects with large numbers of inexperienced programmers, and I think this effect has given C++ the undeserved reputation for being "slower than C".

So, I'd reccommend going for C++, mostly because you can use the c++ (stl) libraries, this will mean you have less bugs and memory leaks to worry about, and more time to profile and optimize the performance.

Good luck!

jdv
+1  A: 

The C code compiled in C++ compiler will be as fast as C code compiled on C compiler.

If you rewrite your application using the C++ features such as Object Oriented or Templates ... etc, you can no longer compare between C & C++ programs, because simply the code is completely different, and you don't have matched features in C

bashmohandes
+2  A: 

I can't imagine what would constitute a definitive (or even satisfactory) answer to this question as posed. I think the question persists because with operator overloading and virtual member functions, it can be hard for a programmer to predict the cost of running a C++ program. With C, all operations are explicit, and the cost model is much simpler and more perspicuous. For example, in C, if you see ++p, you can be confident that the cost is about one machine instruction. In C++, it is quite likely to be similar, but you never know if the ++ operator has been overloaded on some kind of fancy abstraction, like "get the next key-value pair in the hash table". I believe that this kind of uncertainty is one reason for persistent rumors that "C is faster than C++".

Norman Ramsey
+1  A: 

Neither C nor C++ contains any specification of what machine language instructions the languages correspond to. There is no way to associate an intrinsic, absolute speed with even a single operation in either language. You can only compare the speed of an implementation of the language via a particular compiler. However, different compilers for the same language, different C compilers or different C++ compilers, will differ in the machine instructions they output.

Further, different algorithms will result in different speeds of execution for exactly the same input and output. Donald Knuth's books on computer programming contain detailed analysis of how different algorithms expressed in assembly language vary in execution speed. Thus even at the level of machine instructions it is difficult to compare speeds. So in order to meaningfully compare C and C++, it is necessary to eliminate all differences in algorithm and compiler implementation, which is a very difficult task which you can be assured that all of the websites you see quoted here have failed miserably at doing.

To illustrate with an extreme example, one of the language comparison websites gives a test where Perl beats C in a regular expression test. However, since Perl's regular expression matcher is written entirely in C, the comparison isn't actually between C and Perl but between a badly-implemented and well-implemented regular expression matcher, both written in C. That the people who put these benchmarks on the web have not noticed contradictions like this should be a red flag about their competence.

Kinopiko
A: 

It depends on how you write code because you can write c code in c++. If you write typical c program using functions then its faster that c++ which is normally written using Objects

Xinus
+1  A: 

Languages do not have speeds. The speed of a program depends on the implementation of the language and the actual program written. There are many different ways of programming in both C and C++ that trade off speed, robustness, space, high-levelness, correctness, simplicity and other things. There is no reasonable answer to this question. You can generally write code of the same performance in both languages.

Mike Graham
A: 

So what is (was) C++? It was simply C with a preprocessor that added lots of useful features.

Presumably these added useful features run about as fast or slow as what you would write in C if you had to.

It's just that in C++ it is so easy to use those features that you use them even when you don't strictly need to, and then of course you pay the price in speed.

It's like if I go to a restaurant and they have a delicious dessert, and I order it and eat it, and then complain about the calories.

Mike Dunlavey
A: 

C is not inherently faster than C++, but in reality it will be in most cases. The only place it is about guaranteed faster is with casts.

Some of the issues and nonissues:

  1. Object size. No one mentions this but it is the most important issue. C++ generates huge volumes of code if you let it, especially with templates. This slows things down much more than people understand. This is the number one issue where C++ falls on its face compared to virtually all other languages.

  2. vtables. Not an issue. You don't have them in C++ if nothing is virtual, and no one uses them for objects that need speed. Also, to use OOP in C you have the same problem.

  3. SIMD and alignment. Default memory management in C++ is a joke. It's not defined well in the language and unless you work very hard you are guaranteed nothing is ever aligned or can use SIMD instructions without a ton of work.

  4. Casting. C++ treats pointers in a silly manner due to MI, and doesn't easily let you use raw memory. This depends on implementation but you generally have higher cost for casts.

  5. Libs. STL/standard library is so slow and bloated you may as well use java (and don't show me benchmarks optimized to trivial cases to 'prove' me wrong, I know better). Templates can sometimes be faster but in general they become much slower, and with the complex design of the standard library it is godawful. Using templates everywhere like that is like performing brain surgery on yourself.

  6. autopointers. Again, USE JAVA if you are even tempted to use something like this. Much slower than garbage collection, incredibly error prone as implemented by default.

  7. C++ small allocations. C++ tends to have many small allocations, such as with 6. above. This tends to be very slow, and extremely wasteful of memory.

  8. Singletons. You can avoid this nonsense 'design pattern' in C++, but only with a deep understanding of C++ static initialization. Otherwise, you hit a guard variable EVERY SINGLE ACCESS to a singleton. Possibly a lock with every single access! That can bring any program to its knees. Again, if you can't handle dynamic static initialization and this 'design pattern' tempts you, you should be using java or C# in the first place.

Charles Eli Cheese