Hacker News new | ask | show | jobs
by ajax77 5203 days ago
Whether or not you are a C++ fan, templatized algorithms ARE often faster than their C-based, generic counterparts. Any decent C++ compiler should be able to inline generic code while C often relies on function pointers. I'm not saying this is always the case, but often. std::sort beating qsort is a typical argument, though I'm not sure the two algorithms are equivalent excepting language-specific constructs (http://stackoverflow.com/questions/4708105/performance-of-qs...)

As for size, you're absolutely right, though for many scenarios that appears to be less and less a pressing concern. Perhaps the biggest drawback is compilation time.

4 comments

Any decent C++ compiler should be able to inline generic code while C often relies on function pointers.

What makes you think that a decent C compiler can't inline runtime-generic code using void* and virtual functions?

Sure, erasing types only so that the optimizer has to figure the information out again using constant propagation is far from optimal, but the underlying issue is actually source code inclusing vs modular compilation -- most of the speed gain of templates comes from the fact that it only works with the former, whereas C-code traditionally does the latter.

I agree with what you're saying but C can be persuaded to make template like code:

http://attractivechaos.awardspace.com/ksort.h.html

Compilation time is becoming less of an issue as well with compilers getting faster and faster. For example the same codebase using GCC 4.6 and clang 3.0, clang is almost 20% faster at compiling the same codebase.

Even so, making heavy use of templates I have not yet found any major issues or that compile time has increased so drastically that it became a concern for the project.

Thankfully you're right; compilers have come a long way and Clang in particular has done a lot for easing the pains of template programming in a number of ways.

I'm knee deep in the development of several header-based, fully templated libraries, so I still certainly feel the pains of compilation times. And while the tests/samples I deal with tend to be somewhat extreme in their (ab)use of templates, I think you'll still find that the average Boost user would give a lot for yet speedier compilation.

std::sort is stable, IIRC. Otherwise, they are similar; and yes, std::sort is typically faster.

Do note that instruction caches are not unlimited, though: bloated code does have a performance cost (sometimes, caches are hard.)

std::stable_sort exists and is the stable one.