3 ms·
C is absolutely not faster than C++. Generic types in C are typically done through type erasure or an intrusive type. C++ templates explictly allow different
by uxcn 11y ago
C is absolutely not faster than C++. Generic types in C are typically done through type erasure or an intrusive type. C++ templates explictly allow different instances of code to be generated for each of the types. So, the code can be specialized for each type, which most of the time is faster. In general, template metaprogramming allows for drastically more complex optimization at compile time.
The biggest reason to write in C over C++ is simplicity and higher level of control over algorithms and data structures. Portability is another reason though.
- vardump 11y agoVery much right, unless CPU icache limits start to bite. C++ templates can generate a lot of code. For simple functions, templates are usually always a pure win. For example, C qsort is horrible. Function pointer to a otherwise so inlinable small sort function is always going to get beaten by C++ template based sort. But if each iteration of loop needs to fetch 10 kB of instructions because of specialized separately compiled templated forms, suddenly pointers win again. It can also invalidate TLB, branch predictor, etc. caches. But most cases templates are a win. Just remember microbenchmarking can really mislead here, if the program as whole has an icache bottleneck as a consequence.
- cactusface 11y agoYeah, but nothing says you can't specialize your C code.
- uxcn 11y agoAnd C compilers can generate specializations if everything is in the same translation unit. What I was trying to point out is that less abstract doesn't imply better performance. It isn't C > C++ > Python. What the machine ultimately has to do is what matters.
- cactusface 11y agoI think programs written in dynamic languages are generally harder to optimize because they're more likely to take advantage of complex features. Since these languages often compile to C, you can obviously write the same program in C, but you aren't as likely to.