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.
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.
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
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.
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).
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.
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.
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.
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.
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.)
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:
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.
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.
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.
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.
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.
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.
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!
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
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++".
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.
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
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.