datasheets.com EBN.com EDN.com EETimes.com Embedded.com PlanetAnalog.com TechOnline.com  
Events
UBM Tech
UBM Tech
Welcome Guest Log In | Register | Benefits

The Inefficiency of C++, Fact or Fiction?

Authored on: Jun 29, 2010 by Anders Lundgren

Technical Paper

0 24
More InfoLess Info

A widespread "truth" among developers of embedded software is that using C++ results in inferior code size and speed compared with using C. This article will attempt to sort out the facts from the fiction in this statement. By better understanding the underlying mechanisms of the language, a designer can avoid code bloat. This article will also discuss various C++ language features, compare them with C, describe their implications for the ARM code generation, and look at the efficiency of the different ARM architectures.

24 comments
write a comment

No Avatar

daraf Posted Jul 13, 2010

It is my impression that the biggest cost of C++ versus C is that C++ code tends to create and discard enormous numbers of objects. Of course, you can do that in C and you can write C++ in a way that it does not create and discard numerous objects. It is just that the C++ programmers are accustom to programming that way.

reply

No Avatar

Etmax Posted Oct 16, 2010

Maybe the problem is that to be a good embedded SW engineer you need a lot of understanding of the implication for the HW and the real world (code size/speed) that certain functionality brings with it. I was debugging a device once where the engineer computed a production variation dependent translation factor in an 8mS loop then had to put all these watchdog pats everywhere in the code so the dog wouldn't timeout. This meant that no matter how the code failed it was always going to be able to pat the dog :-). This quite apart from the sluggish performance it introduced. This was in 'C'. I changed it so it computed the factor at start up (Once) and reused it. The programmer was a PC developer in a past life I think, and didn't understand the ramifications of having only 1 MIP available. I will say though, that because C++ removes a lot of the complexity from the developer, it invariably results in poorer code because if you can't afford the time to develop in 'C' then you probably can't afford the time to actually do a complete run time analysis on the finished product. Also, if you write embedded code in C++ in a manner that is as efficient as in 'C' then you are most likely not using the C++ extensions. I Have to agree whole heartedly with betajet, I have often referred to 'C' as a "device independent assembler", and in the deeply embedded space it is best used as such.

reply

No Avatar

betajet Posted Jul 16, 2010

In general, you have to be much more explicit about function calls and dynamic memory allocation in C, so you have a much better idea of what your program is really telling the computer to do. In many ways, C is a "portable assembly language" rather than a high-level language, and one tends to produce better code by thinking of C that way, especially in embedded applications. C++ hides this from the user, so it's easy to create inefficiencies without meaning to. There's an old joke: "C gives you enough rope to hang yourself. C++ gives you enough rope to tie up everybody in your neighborhood, rig a small ship, and still have enough left over to hang yourself from the yardarm."

reply

No Avatar

fred571 Posted Dec 10, 2010

There is no dynamic allocation in C++ unless the new operator is used. This does occur within the standard template library, but for your own code, the clue is the keyword new. I consider this to be as explicit as a call to malloc is in C.

reply

No Avatar

DKC Posted Jul 20, 2010

C++ is probably more inefficient in terms of code size, however the ability to use inheritance and function overloading allows you to tune versions of code more easily, i.e. you can move a bunch of decision making from run-time to compile-time or instantiation (class object creation). Calling virtual functions may incur redirection costs and blow branch-prediction, but it also replaces decision making about what to call. Programming "by exception" is an anti-pattern - http://en.wikipedia.org/wiki/Anti-pattern#Programming_anti-patterns STL is general purpose code, and the implementation is poor - I avoid using it.

reply

No Avatar

WaltKaras Posted Jul 22, 2010

Meh. Tends to oversimplify. You need to have some idea of what the generated object code will look like, which can depend on how good your tools are. Virtual functions and base classes are cheap but the "make everything virtual just in case" approach should still be avoided in highly constrained systems. Templates and inline functions are free if your tools make sure there is no duplicate object code, but in practice I doubt most existing tools meet this standard. Exception implementation can have virtually no speed overhead in exchange to a considerable size overhead. There are tricks that can avoid generation of superfluous exception-handling object code, but that somewhat negates the advantage not explicitly handling exceptions with function return values. One issue that can be a show-stopper is environments where machine code needs to be explicitly paged in (not by an internal interrupt). Code to do this in C I think can be fairly portable, but in C++ it's non-portable at best and impossible worst-case. I think this may be the only non-aesthetic reason that the Linux Kernel has not been rewritten in C++ .

reply

No Avatar

WaltKaras Posted Jul 22, 2010

Practical note: the eetimes website will behave in a surly way when inside the linkedin.com frame, so best to delete it (or so it was for me).

reply

No Avatar

jianqiang Posted Aug 11, 2010

I think that the author has lost his/her way in indulging in the C++. The simple fact is that the C++ programming language is not written for the embedded design, but for the large application/operation system. And the C is written to be "portable assembly language" as Mr. betajet pointed out. The embedded design has to deal with the precise control of the the hardware. The most precision/flexible tool for the embedded design is the assembly language. But it has the disadvantage of inefficiency. The C is written for the very purpose of adding the harware-control flexibility to the high-level programming language, therefore, it is the best and most efficient tool for the embedded design. The C produces much faster and smaller codes than the C++ does when dealing with hardware control and numerical calculation, such as FFT.

reply

No Avatar

joej1 Posted Aug 30, 2010

jianqjianq You probably should read the paper before posting those opinions. ;-)

reply

No Avatar

boffin Posted Aug 11, 2010

Anders Lundgren is more concerned with code size than code performance. Both depend on the compiler and the optimizations though he is right in his conclusions about code size. As regards performance, my own experience is that out of the box pure C++ leaves much to be desired. The STL tries to be something for every circumstance and you do far better to roll your own routines. Inline assembler is obviously an advantage since C++ compilers will rarely get the best code. As an example on standard Intel PC processors: in CFD there is often the need to invert a tri-diagonal matrix - that is far better done using SSE instructions, yet no compiler I have tried does this. On VLIW processors it's the same problem - the compilers are too naive. Of course on some machines CUDA may be the ultimate answer, but then you must parallelise everything. (I work writing high performance video and Computational Gas Dynamic codes where every millisecond counts).

reply

No Avatar

BMN Posted Aug 19, 2010

RTTI doesn't necessarily depend on the string name of the classes. I think most compilers are smart enough to avoid this and use another means to identify classes.

reply

No Avatar

PAVANSAM Posted Aug 31, 2010

 encapsulation/classes - FREE  namespaces - FREE  inlining - FREE  operator overloading - FREE  constructors/destructors - FREE  references - FREE  virtual functions - CHEAP  templates - EXPENSIVE  STL (Standard Template Library) – EXPENSIVE  RTTI – expensive  exceptions - expensive concept is free but the implementation cost of the final req using those concepts in c++ would be definitely high compared to c !!

reply

No Avatar

Reagan.Thomas Posted Sep 10, 2010

Take a seasoned C programmer, teach them C++ but make sure their understanding is such that they can picture in C or assembly each piece of C++ they encounter in their study. Then they'll know how to make efficient C++ code when necessary... even if they have to resort to C. I suppose you could do the reverse too; teach a C++ coder C and at least some assembly and explain what C++ is doing in terms "closer to the metal." In any case or language, when efficiency is critical, so is understanding the relationship between the code and the computing resources available.

reply

MikeLC Posted Sep 30, 2010

C++ properly done, is a great language for any kind of code, including embedded. I liked the article showing what constructs were to be used and which to be avoided. There's a great table near the end of the article. It's nice to see that the major benefits of the language, inheritance, encapsulation and other class object-oriented aspects have little or no affect on efficiency. Only RTTI, Exceptions and STL are really inefficient in embedded systems, and I personally only use some of the STL, which I've found is only inefficient in certain cases. I would make one point: for the novice be absolutely sure you pass by reference (or pointer) to avoid copy constructor over-usage. Also, there is nothing wrong with using c-constructs such as structs in C++.

reply

No Avatar

Vincent.Claes Posted Nov 12, 2010

does someone has a good reference article comparing C++ and Java for embedded systems? Which OO language do we have to learn as an embedded software guy?

reply

Jeff Dickey Posted Nov 16, 2010

The idea of carrying around a JVM on an embedded system makes me almost violently ill. Good luck with that (you'll need it)… C++ will always have the question of "which C++ features will you use/declare off-limits?" Though I generally agree with PAVANSAM's list above, eliminating "expensive" won't cut it for many, many C++ projects Have you taken a look at Objective-C lately (2.0+)? The more I work with it, the more I look back at the pitched battles fought against C++ and shudder. Several alternatives for toolchain, including decent gcc and LLVM implementations.

reply

No Avatar

eembedded_janitor Posted Nov 28, 2010

Have a look at Lejos (google will find). This is a JVM for the Lego Mindstorms platform. It runs on a small ARM with less than 64 k of memory footprint. The actual JVM part is quite small (approx 20k). I have yet to see any benefit in using C++ for embedded systems. C does a fine job.

reply

No Avatar

eembedded_janitor Posted Nov 28, 2010

Jeff: If you choke on a JVM.... Tektronics made an oscilloscope using Smalltalk. I used one of these and it had the annoying habit of deciding to do garbage collection as you turned a knob. That would cause a delay of a large part of a second causing you to zoom to far. Objective C is interesting, essentially being a fusion of C and smalltalk.

reply

sharps_eng Posted Dec 2, 2010

Here we go again - please, please, before commenting on language issues, consider if your example is actually about weak program design which is of course truly language-independent! Also, like it or not, embedded Linux (and bigger) systems are here to stay (and one is in your pocket at this moment I should think). C++ can be used happily for real-time work, but only if the programmer first knows what real-time work actually means.

reply

No Avatar

fred571 Posted Dec 10, 2010

My suggestions for C++ features that should be used first by C programmers: - private member data: clearly separates interface from implementation and enlists the help of the compiler to catch those rascals attempting to jump the fence. - constructors: YOU write the initialization code for the object's member data. That initialization function is automatically invoked as a byproduct of user code making one of the objects. Don't tell me you never forgot to initialize an element of a C structure! - Stroustrup's "resource allocation is initialization": THE BEST coding technique for reliably releasing a resource before exiting a code block. - virtual functions: codify "this is a special kind of that" relationships. They're everywhere. - default parameters: let your callers omit call parameters that can be optional. - const: this is a special case of the principle of least privilege. jelliott (you know what goes here but a spam parser does not) validatedsoftware.com

reply

No Avatar

fred571 Posted Dec 10, 2010

I hope to see an investigation of the run-time and code space costs of exceptions. Remember that a properly written C program checks for errors, so factor that in when making a comparison to equivalent C++.

reply

No Avatar

Scott.Bonomi_#1 Posted Dec 29, 2010

This is a grand case of poTAYtp vs poTAHto. Each language has the areas where it excels and the areas where it could be improved upon. There are some nice advantages to C++ which can be used to encourage encapsulation of modules. There are also some disadvantages which can mostly be avoided by good embedded coding practices. I do not expect any language to be correct for all implementations. I do expect to be able to bring a language tool out of the toolbox that is appropriate for the task at hand. Whether that tool is C or C++ (or Ada or FORTRAN or Forth or Smalltalk or Lisp or Jovial or....) is dependent on the requirements of the system under design and the skills of the person or team working the problem. One could even use Java if desired; but that depends a lot on the system target. If you are using an ARM7 with 32k of Flash and 16k of RAM, it would not really lend itself to adding a VM using 20k unless your application is really, really small. This, of course, depends on processor selection and picking a processor that is $0.50 cheaper may be important if you are going to make several million devices. If you are only making ten systems, the cost of a more capable processor is probably lost in the noise. I believe that what we ought to bring away from this paper is that there are ways to avoid or alleviate most of the "historical tribal knowledge" issues with C++ in an embedded system and that there are some advantages of using it. Dan Saks has written extensively on how to implement useful, and somewhat portable, real time constructs in C and C++. I believe that the advantages outweigh the disadvantages in ost cases. This opinion is probably colored by the type of system I tend to work on; one which has a long maintenance life after the first delivery. In this case, the advantages of encapsulation, and supporting module re-use, become more important. Scott Bonomi sbonomi at cei.to

reply

No Avatar

adkohler Posted Jan 20, 2011

In our shop, most of the "gotchas" mentioned in the whitepaper--and many posts--are well known and understood. We never use exceptions or create new objects after initialization. We know most STL is expensive and that there are better alternatives. And knowing is half the battle. :)

reply

No Avatar

Bear1959 Posted Feb 28, 2011

Unless you need the extra bells and whistles of C++ it is usually best to keep to the KISS principle. In most cases C does an excellent job for embedded work. Of course, if for whatever reason (others in the shop are using C++, or you need the extra functionality of C++) then go ahead and use that. However, use the simplest language that will get the job done with excellence as more complex schemes just add unnessary cost of learning, development, and maintenence. All things are possible, but not all things are the cheapest or fastest.

reply

Please Login

You will be redirected to the login page

×

Please Login

You will be redirected to the login page

×

Please Login

You will be redirected to the login page