Cost of enum-to-string: C++26 reflection vs. the old ways

· coding · Source ↗

TLDR

  • Benchmarks on GCC 16.1 show C++26 reflection’s compile cost comes almost entirely from <meta> inclusion (~155ms/TU), not the reflection algorithm itself.

Key Takeaways

  • X-macro with const char* is fastest: ~27ms/TU for N=4, beating even the <meta> include-only cost of ~181ms.
  • Reflection algorithm scales at ~0.07ms/enumerator, nearly identical to a hand-rolled switch, once header cost is excluded.
  • PCH for <meta> cuts reflection compile time ~2.3x (187ms to 81ms for N=4); C++20 modules in GCC 16 do the opposite, adding ~2.2x slowdown.
  • enchantum scales with configured scan range, not actual enum size, making it expensive for small enums (~24ms overhead regardless of N).
  • At 500 TUs, reflection costs ~94 CPU-seconds vs ~13 seconds for the const char* X-macro approach, though parallelism reduces wall-clock impact.

Hacker News Comment Review

  • Commenters flagged that GCC 16 results may not generalize: Clang’s C++26 reflection is not yet available for comparison, and module behavior in particular is compiler-specific.
  • The C++26 reflection syntax drew sharp criticism for readability; several commenters noted it looks foreign even to experienced C++11/14 developers, undercutting the “no boilerplate” framing.
  • Compile-time debugging of consteval reflection code remains an open gap; static_assert is the main tool, with no step-through debugger support available.

Notable Comments

  • @dataflow: Questions whether enchantum can handle duplicate enum values, discontiguous ranges, or MSVC – limits not addressed in the benchmark.
  • @king_geedorah: “Another win for X macros and for C style in general” – frames results as a vindication of preprocessor approaches despite ergonomic costs.

Original | Discuss on HN