September 14, 2019

Is C faster than C++?


The question was asked recently in a blogpost somewhere in the internet. For measure the performance on an objective basis, a pi calculating routine was written which was realized with the same algorithm. The first routine was compiled with gcc, the second one with the C++ compiler. The result was, that the execution time in seconds was exactly the same.
In my own experiment i came to the same conclusion. The runtime speed of the binary file is the same, and even the program size in bytes was the similar. Does that mean that C++ is comparable to plain C? No that is not the conclusion, because we have to take a broader look into the ecosystem. A c++ compiler is more difficult to realize than a C compiler. And a book which describes C++ has more pages than a book which gives an introduction to C. That means, C is the baseline, and the C++ compiler is trying to imitate the standard.
Instead the answer has to do if someone likes to program object oriented or not. Most current libraries are not written in C++ but in normal C. The reason is, that the increased complexity of C++ doesn't provide an advantage so the programmer stay within the C universe and ignore the extension of C++. If they want to program object oriented they are switching from C to a scripting language like PHP or Python. There is a second reason why plain C is recommended over C++. If the aim is to improve the performance of a program there is a need to use pointers and program close to the machine. This results into a programming style which is called c programming. That means, the programmer allocates manual memory, and gives the pointer to a datastructure to a subroutine.
Using this kind of tricks in context of a C++ is possible but it is not compatible with object oriented programming. That means, the C++ language is used as some kind of C language and the question is why the OOP extensions are available. On the other hand, the programmer can not ignore pointers, because then he will loose all the performance. It is important to decide either for lowlevel hardware programming or high level object oriented software engineering.
Software engineering has to do with designing an application. It is realized by drawing UML charts, creating prototypes in a scripting language and write throwaway code. In contrast, the production ready code is written in low level C language which doesn't provide object oriented features but is using the CPU as fast as possible. It make sense to separate both steps.