logoalt Hacker News

afdbcreidtoday at 3:35 AM4 repliesview on HN

Is C++ more performant than C? I find this hard to believe. C++ does not have any construct that cannot be replicated, or is not common, in C. The only candidate is using virtualization and void* pointers instead of monomorphized generics which some C code does for the lack of better options, but that's not a problem in Rust as well.

If anything, Rust has the potential to be more performant than C due to its aliasing rules (C has `restrict` but it's rarely used, standard C++ does not have even that). The current perf stats show it does make Rust code faster but just a little bit, although we don't utilize the full optimization potential currently (LLVM does not do many possible optimizations here, and `noalias` is weaker than Rust's aliasing rules). It can also affect autovectorization, and if it does the effect could be dramatic.


Replies

jandrewrogerstoday at 4:19 AM

Modern C++ metaprogramming materially impacts performance in practice. I’ve done performance engineering for decades in both C and modern C++ and I would assert that the difference isn’t arguable.

The poor applicability of auto-vectorization is another area where C++ is strong. You can transparently codegen e.g. AVX512 from intrinsics directly in C++ in contexts that would be opaque to auto-vectorization and difficult to generalize in C. This allows you to get some degree of “auto-vectorization” where the compiler can’t see it because it works at the wrong level of abstraction.

With sufficiently heroic efforts you can write C that matches the performance of C++. I’m not arguing that. Virtually no one writes C to that standard, including myself when I was writing high-performance C because the effort was too high, so it is a bit of a strawman.

It is the difference between theory and practice. All code bases have a finite budget. C++ can do a lot more optimization in the same budget as C.

show 1 reply
loegtoday at 3:47 AM

C++ you get templated generic algorithms that in practice no one really does with C because macros suck too much. So in C typically you'd have a runtime generic routine that doesn't inline. A classic example here is qsort() vs std::sort().

show 1 reply
smallstepformantoday at 3:59 AM

c++ uses rich type system to avoid aliasing when it can, as well as template meta programming.

Eg: delete_scene(void *arg) vs delete_scene<T>(T *arg)

fithisuxtoday at 3:52 AM

You can write C style C++ and enjoy the same benefits.

In Twitter a user explained me that it is common in embedded space.

You do not need the OOP, RTTI, exceptions.

Like C with most use cases of preprocessor replaced by generic programming.

show 1 reply