Mar 22, 2011

The Cost of Type Safe Code

Brother Can You Spare a Dime (of RAM)?

I tend to evangelize the C++ Library in embedded programming for it's ability to produce type safe code. Even though I know most embedded programmers on the NetBurner have managed to cause traps from easy to make mistakes with printf and sprintf I don't believe I've won many (any?) converts. One question I've heard raised is the memory cost of using <iostream> and <sstream>. That's a legitimate concern in the embedded world. One reason I like the NetBurner platforms is that most of the ones I use have gobs of memory. The NIST definition of a gob is 2MB Ram and 8MB Flash. A half a gob is still 2MB RAM and 4 MB Flash. I decided to take a look at what the costs of using the the C++ Library as well as some advanced features like the STL and templates.  I also experimented with some of the compiler optimization settings.



It turns out that the heftiest price is paid up front when including <iostream>, Flash took 140K hit and Ram took a 290K hit. For the hardware I use this is well within my pain threshold, but there are some smaller memory SBCs out there were a 290K is probably unacceptable so it can be useful to know the costs. In the table you can also see the results from some random tests I ran. I was interested in seeing if there were any surprising big jumps from using STL containers, algorithms, virtual functions, exceptions or templates. I'm happy to report that after using <iostream> the cost of the STL seems downright cheap.
If you're a NetBurner programmer and you're interested in the code I added I've included some screenshots below of the added class. Main just had some calls to the various functions.
Here's the header for TestClass.h (which includes the two templates)


And here's TestClass.cpp


About Me

My Photo
Tod Gentille (@todgentille) is a software consultant and author for Pluralsight. He's been programming professionally since well before you were born, and running his own software consulting business for most of that time. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.