r/programmer • u/awesome-alpaca-ace • Oct 31 '26
Question Template Metaprogramming's Performance Limitations
A while back, I tried to build an entire dictionary with scores for Scrabble using only C++ templates. I quickly hit compiler limits, and removing those, I quickly hit memory limits on my machine with 64GB.
I then built it at runtime, because I had no clue how I could have optimized template metaprograms, and I still do not really as I have little experience with them.
I have been building a battle simulator that uses a heuristic to control the actions of the agents, and thought how cool it would be to write parts of it as a template metaprogram, but there is no way that will work if the word trie for Scrabble failed.
Is this partly an implementation problem or are compilers just not suited for template metaprograms? Is it possible to create template metaprograms that are as fast as their runtime counters or is there some theoretical limitation of a compiler's implementation to make that infeasible?
1
u/FloweyTheFlower420 Oct 31 '26
templates are slow, constexpr functions are a bit better
1
u/phire Oct 31 '26
It's not the compilers that are at fault. Template metaprograming is simply not well suited to be compiled.
1
u/cossarian 28d ago
Same here. Hit the memory limits making interpreter embedded in C++. That was just a proof-of-concept though.
1
u/scallywag_software 28d ago
It's an implementation problem. There's nothing really special about template metaprogramming .. the C++ implementation is just hot garbage.
My evidence: One of the early demos of Jon Blow's JAI compiler compiled and ran a (simple) game at compile time. Opened a window, did all the game stuff like entity updates, collision, etc.. drew using the 3D accelerated API .. the whole thing. EDIT: At the time, the compile time program was jitted into bytecode and interpreted, so IIRC it ran at about half speed. That was like 5 years ago, it's probably much better now.
Secondary evidence: I wrote a template metaprogramming language as a replacement for C++ templates. The next version will actually compile the metaprogram to machine code the same way your regular program does, and it'll run at the same speed as any other piece of code in your program. You'll be able to run your entire program at compile time, exactly the same as it runs at runtime.
Anyone that tells you that there's something special or hard about compile time metaprogramming is confused.