User:Rincewind82/sandbox

Verbose assembly and code bloat
There has for a long time been accusations about C++ generating code bloat. In order to measure this in a fair way we should use the same compiler to compare idiomatic code in C against modern C++ using the C++ standard library. Here we have the simple task of initializing a string array and to print it out. We'll get the opportunity to use some of the most fundamental constructs like strings, arrays and IO.

In this shell script we compile our test. We use g++ and let the preprocessor define if we want to compile C or C++. For C exceptions only generates some data structures that the linker removes later. By removing them directly with "-fno-exceptions" we make the C code cleaner. We also remove the DWARF debug information with "-fno-asynchronous-unwind-tables -fno-dwarf2-cfi-asm". This has no influence on the binary sizes but removes some additional noise from the assembly code.

From the binary sizes here we already see some signs of code bloat. The C++ binary is much larger than the C binary. They are both solving the same simple task of writing out a string array. The only difference is that we are using C++ class templates and to do it in the C++ case, and primitive datatypes in the C case. To be fair; some of this code bloat can later be removed by the linker when several source files use the same class templates further on. Our real interest is how the function "StringArrayTest" looks like. The code bloat we are finding there is there to stay.

Here we have the C++ version. We see many slow call instructions to IO functions and various constructors/destructors. The compiler is unable to optimize them away, creating significant code bloat compared to the C version. When creating multiple functions printing out different strings, the code bloat is there every time. In contrast; even when using printf and "char strings[][STRING_MAX]" the C version keeps its compact assembly output. The problem doesn't seem to be with the C++ language itself. Using std::array instead of std::vector/std::string, and using instead of creates the same compact assembly output as the C version. The problem of code bloat seems to be with the  and the STL with it's heap dependent template classes.