r/cpp • u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting • Mar 06 '26
the hidden compile-time cost of C++26 reflection
https://vittorioromeo.com/index/blog/refl_compiletime.html
123
Upvotes
10
u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Mar 06 '26 edited Mar 10 '26
NOTE: the original measurements were incorrect. See here.
I ran some more measurements using
import std;with a properly built module that includes reflection.I first created the module via:
And then benchmarked with:
The only "include" was
import std;, nothing else.These are the results:
So PCH actually wins for just
<meta>, and modules are not that much better than PCH for the larger example. Very disappointing.23
u/Paradox_84_ Mar 06 '26 edited Mar 06 '26
I'm also experimenting with reflection, modules and gcc-16. I used both cmake and manual compilation, I never needed to do "include <meta>" only "import std;"
Can you measure again with modules, but exclude the compiling of std module?
Fyi, I used this to compile the std module: " g++-16 -std=c++26 -fmodules -freflection -fsearch-include-path -fmodule-only -c bits/std.cc "
And this to compile the executable: " g++-16 -std=c++26 -fmodules -freflection main.cpp -o main "
60
u/RoyAwesome Mar 06 '26
Ok, so, yeah, it has a cost. I dont think anyone was ever saying reflection would be completely free.
The cost of reflection needs to be compared against a compiler toolchain that generates reflection information and feeds it back into the compiler. This process takes over 10 seconds in Unreal Engine, and compared to that, cpp26 reflection is fairly cheap!
I believe clang is working through a proposal to create a kind of bytecode vm to process constexpr code in C++, rather than their current machinery. This might speed up compile times in this space.
11
u/38thTimesACharm Mar 06 '26
My first thought was "
import stdwill fix this," but then you say this:But does that number include compiling the
stdmodule? The entire benefit ofimport stdis that you only have to do that once, or whenever you change project-wide compiler flags. Debugging and iterating should be much faster.7
u/germandiago Mar 06 '26
What did you do to compile your whole project in 5s?
Do you use precomoiled headers besides removing most STL headers? How many cores are you using for compilimg and which kind of CPU?
Thanks!
2
u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Mar 10 '26
UPDATE AND APOLOGY:
As correctly pointed out by /u/wreien, the Docker image I originally used contained a version of GCC 16 built with internal compiler assertions enabled. This completely skewed the data and unfairly penalized GCC.
I sincerely apologize to GCC maintainers and the readers for my mistake -- I should have verified the container’s GCC build flags before publishing, as I had assumed that GCC had been built in release mode.
I have since re-run all benchmarks on a proper release build (using fedora:44 as suggested by /u/jwakely), and the article has been fully updated to reflect the accurate (faster) numbers.
NOTABLE UPDATES:
<print>is still very expensive, but not as bad as before (from ~840ms to ~508ms).Please ensure to take a look at the updated version of the article to see a more accurate (early) picture of C++26 reflection compile-time overhead.
The new (accurate) data is much less concerning.
9
u/tartaruga232 MSVC user, r/cpp_modules Mar 06 '26
I would read it if it were black on white.
9
u/No-Dentist-1645 Mar 06 '26 edited Mar 06 '26
You're telling me that when I tell my code to run calculations at compile time... the compile time increases? There's no way /s
I thought the tradeoff was very clear for most developers: the idea is to move the time of expensive compilations from runtime into compile-time so that we can deliver faster binaries to end users, not to "magically make the time of computations disappear"
2
u/JVApen Clever is an insult, not a compliment. - T. Winters Mar 06 '26
Any measurements available with import std?
2
u/vali20 Mar 06 '26
Why can’t he pull in the standard library as a module and call it a day?
62
u/FlyingRhenquest Mar 06 '26
I got the impression that Reflection was still going to be less expensive than the heavily templated metaprogramming solutions that you used to have to use for some of those compile time tricks previously. Sutter said something about it being easier to parse than recursive template code, anyway. It's certainly easier to reason about.
It would be really interesting to compare the compile time of a heavily templated compile time library like boost::spirit::xi with a reflection-based version that offered similar functionality. It'll probably be a while before we see a reflection-based replacement for something that massive, though.
4
u/seanbaxter Mar 06 '26
These are interesting numbers. 6.3ms per reflected struct (or even 2.2ms) struct is incredibly high. 1,000 structs is a small number (consider what comes in through the system headers) and we're talking about integer number of seconds for that?
3
u/feverzsj Mar 06 '26
I just give up on optimizing compile times. Using unity build on decent hardware seems to be the optimal solution.
7
u/TheoreticalDumbass :illuminati: Mar 07 '26
i am getting lost in all the comments, just want to say 1) thanks for actually benchmarking, 2) i expect/hope explosion in reflection/constant evaluation usage will also prompt optimizations in compilers
11
u/TSP-FriendlyFire Mar 06 '26
I understand where you're coming from with your desire to minimize dependency on the STL, but I fear that that particular recommendation is going to be misinterpreted to the worst possible extent and thus I really can't agree with it.
I'm currently dealing with a fairly large codebase that obviously had a tendency to not use existing libraries and features, preferring to reinvent the wheel time and again. A lot of it comes down to historical justifications and hazy claims of "performance" or "flexibility", but ultimately what you end up with, unless the architects and programmers really know what they're doing, is a worse version of the STL.
The custom types that I've seen that replicate the STL (and I've seen many at multiple employers) invariably lack some of the features (namely, allocators, even though it's a huge piece of the runtime performance puzzle), do not get follow-up improvements (the code was written against C++98 so it remains a C++98 feature) like
constexprsupport, and often also rely on UB to boot (because the developers were nowhere near as knowledgeable about C++ minutiae as STL implementation developers are, unsurprisingly). You end up with a fragmented codebase where you sometimes have both the STL and the custom types used side-by-side with no rhyme or reason. I get that the STL is big and unwieldy and slow and doesn't get new features particularly quickly, but for 99% of codebases out there, using the STL properly will be substantially better for the health of the code than Timmy's custom vector type that doesn't handle half the thingsstd::vectorcan and runs worse on top. I'm okay with sacrificing some amount of compilation time to that.Similarly, I much prefer reflection's use of
std::vectorover introducing a new type that's just for reflection. Reflection is complex enough as it is, I think it's valuable that it uses familiar types (which means it can also reuse your existing code that takesstd::vectors as input!). And please, P4329's suggestion to replacestd::spanwithstd::initializer_listof all things (when the latter is one of the clunkier and most annoying parts of the language) wasn't particularly appealing, much the same as once again C-ifying C++ withconst char*s instead ofstd::string_views. ImGui's insistence on using raw pointers everywhere remains one of my biggest issues with the library, so I'm glad the STL is moving forward with modern types instead.TL;DR I argue most codebases would benefit from using more STL, not less, and the compile times are a small price to pay for the improved maintainability (and sometimes even better performance and flexibility). Likewise, the decision by the reflection authors to leverage the STL's existing rich type infrastructure will make it easier to connect to existing code while reducing the (already high) cognitive load of learning and using
std::meta.1
u/James20k P2005R0 Mar 06 '26
I've always thought it was slightly odd that standard library headers like <ranges> and <algorithm> aren't a grouping of smaller headers, that you could individually include for whatever you actually need. So instead of pulling in massive catch-all headers, you could just nab the bits you actually want
I think this is one of the reasons why extension methods would be nice for C++: often we need something close to a forward declared type (eg std::string) but you know - with an actual size and data layout. I'd be happy to be able to break it up into just its data representation, and the optional extra function members in separate headers to cut down on compiler work where necessary
Its surprising that PCH doesn't touch the cost of <print> though, I'd have thought that was the perfect use case for it (low API surface, large internal implementation), so I'm not really sure how you could fix this because presumably modules won't help either then
1
u/Resident_Educator251 Mar 06 '26
C++ will always be slow to compile. I work in a mixed project with c and c++ it’s just so sad to see c built basically instantly by comparison to c++.
Doing anything interesting with templates just screws with the times.
Maybe some lame plane head and cpp combo app with zero templates would be somewhat better but then why use c++.
3
u/CornedBee Mar 08 '26
Compile times are annoying, yes - but I really do have to wonder what freestanding implementations will say about this.
Reflection is a core language feature:
std::meta::infois a fundamental type, the result of the reflection operator and the argument of the splice constructs.And yet, it is not possible to do anything interesting with reflection without including
<meta>. And<meta>, at least according to the current draft, is not part of the required freestanding header set. This despite there being absolutely nothing about reflection that can't work in an embedded or otherwise typical freestanding context: obviously it's all done at compile time and no limited system ever sees anything of it.But
<meta>also requiresstd::stringandstd::vector, and those aren't part of the freestanding library either! So how does that work?Will freestanding C++ implementations simply not provide reflection beyond "reflect a construct and splice it elsewhere"?
Will they provide
<meta>and<string>and<vector>, but fail compilation if any of it finds its way to runtime?Will they invent a new extension to make features only available to
constevalfunctions, so other code isn't even aware ofstd::string?Did anyone think this through?
Maybe I'm totally off-base and this isn't an issue at all. TBH I never worked with a freestanding implementation. It just sounds like a huge issue.
1
u/slithering3897 Mar 06 '26
Yes, I worry about compile times too. Although, modules are the end goal, so I'll ignore header overhead.
Then all that's left is further template instantiation and constexpr execution.
Clang people have said that constexpr should be fast, one day. But I still worry that this use of
std::vectorin<meta>, and use of range algorithms, will mean that the compiler will waste time in the internals of std lib implementations.Or template instantiations will dominate. Maybe
-ftime-reportwill tell you.I'd like to investigate myself, but still waiting for that VS implementation...
0
u/Realistic-Reaction40 Mar 07 '26
this is the kind of thing that gets discovered in prod when someone adds reflection to a hot path and suddenly CI times double
-2
u/bla2 Mar 06 '26
I agree with you, thanks for writing this.
I'm a bit surprised there are so many people defending dependency on standard library headers, and them being slow to compile. I agree that C++ with as little of the standard library as possible is much nicer.
-1
u/sera5im_ Mar 08 '26
wait they're adding reflection? will they add reference tracking too?
0
u/[deleted] Mar 06 '26
[deleted] — view deleted comment