4 ms·
The one area where C++ can be a lot faster than C is in places where C uses a function pointer where C++ uses a function template. The standard example is sort
by Someone 7y ago
The one area where C++ can be a lot faster than C is in places where C uses a function pointer where C++ uses a function template.
The standard example is sorting. Say you’re sorting an array of integers. Then, C’s sort has to (1) call the comparison function passed as an argument, whereas C++’s std::sort can inline the comparisons into a single instruction.
(1) if the source of the function passed in is visible from the compilation unit, I think the C standard allows the compiler to compile a specialized version of sort in the same way C++ can, but I’m not aware of any compiler that does that
- kabdib 7y agoRight, inlines are hard to beat, and they are not part of the C standard (which is kind of mind boggling, I mean . . . honestly, what year is it?). Still, the benefit of inlines diminishes as the size of the inlined functions increases (you start paying penalties for extra cache lines full of code, and the percentage of time in function call overhead gets small in a hurry). The linker can get into the inlining game, too, by the way, if the win is sufficiently big. I have scars to prove it. :-)
- colonwqbang 7y agoWhat do you mean by "inlines are not part of the C standard"? The standard talks about visible behaviour of programs, never the concrete implementation.
- kabdib 7y agoYou're correct about C99. I cut my teeth on K&R; C99 has inline declarations.
- ncmncm 7y agos/The one area/One area/. Another is where a better algorithm is available in a library than would be convenient to implement in custom form in C. C++ libraries get a lot more attention to optimization than C libraries because it pays back much more. For example, there are really excellent hash table libraries in C++ that would be unimplementable, as a reusable library, in C. C hash tables are typically hand-rolled in place.
- colonwqbang 7y agoA C compiler can certainly also inline functions, as long as the definition is visible. Neither is there any guarantee that all C++ template instantiations will be inlined.
- Someone 7y agoThat’s true, and C compilers do so for short functions such as memset and strcpy (and doesn’t even need the definition to be visible), but historically, they haven’t for longer functions, and, I guess, many programmers wouldn’t like it if, say, they generated ten specialized copies of sort, speeding up those calls, but also blowing up executable size. On the contrary, C++ programmers historically expect all templated code to be specialized. It’s only relatively recently that C++ linkers started to merge copies of template expansions.