Originally Posted by
JVene
Let me extend this discussion with yet another assertion about OOP in C++ vs C. I take this again from a Stroustrup interview, but from a more recent memory.
A matrix library was written as a template class in C++. A counterpart was written in C. These are doctoral candidates or other PhD's like Stroustrup, so we must assume they were written by competent hands.
The C++ version outperforms the C version, and that might be surprising. Stroustrup explained why. It appears that when creating generic code, it's possible to describe a problem such that there's greater opportunity for the compiler to 'understand' the code, and optimize it. Without the example in hand I can't say why, but his assertion was the C compiler didn't get as much information as the C++ compiler did, by virtue of the way the problem is expressed. As such, the compiler optimized the code better in the C++ version.
Here again, I think it safe to say, it was easier for the compiler to optimize - because the expression of the problem was better. Certainly, the C version was possible.
Another illustration that's much clearer, sorting. The C runtime qsort was compared to a sort in the STL. The STL sort is faster in some situations, and here again I rely on Stroustrup's explanation. qsort requires a function pointer as the comparison predicate. Sometimes that's the only way to describe the predicate. However, there are many sort situations that depend on primitive types, in which case the comparison is trivial. The STL provides a means of describing the sort predicate such that the compiler can optimize that into a primitive comparison without generating a function call - inlining the comparison. qsort's dependence on a function pointer makes this optimization impossible.
Even Stroustrup pointed out that it's certainly possible to write a qsort the specifically optimized the comparison. Certainly a CFront output would have done so from the template example, too. The point is, with the STL, the optimization is easy. To make one's one qsort optimization is not.
The expression of the problem in the STL gives the compiler information unavailable to qsort. It was the summary point of Stroustrup's response that the there's a richer expression potential in C++, which gives more information to the compiler for optimization, and I submit that makes things a little easier, too.