Skip to content

Avoid O(N^2) template instantiations in no_duplicate_field_names - #799

Merged
liuzicheng1987 merged 1 commit into
munich-data-engineering:mainfrom
clockblocker:optimize-no-duplicate-field-names
Nov 27, 2026
Merged

liuzicheng1987 merged 1 commit into
munich-data-engineering:mainfrom
clockblocker:optimize-no-duplicate-field-names

Conversation

@clockblocker

@clockblocker clockblocker commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Addresses #350 (eliminates the recursive template instantiations that trigger MSVC C1202 on large field counts).

Replaces the $O(N^2)$ recursive template expansion in rfl::internal::no_duplicate_field_names (iterate_over_i → iterate_over_j → compare_two_fields<Fields, _i, _j>) with a single constexpr sort-and-scan over std::array<std::string_view, N>.

For an 80-field tuple or rfl::Literal, the previous implementation instantiated $\binom{80}{2} = 3{,}160$ compare_two_fields function templates per type.

Compile-time benchmark

Single TU with one 80-field rfl::Tuple<rfl::Field<...>...> and one 80-entry rfl::Literal<...> (-std=c++20 -fsyntax-only):

Compiler Before (main) After
Apple Clang 17 1.21 s 0.45 s
GCC 16 2.22 s 1.36 s

Key details

  • Uses a small in-place constexpr Shell sort over std::array<std::string_view, N> (no <algorithm> dependency) and evaluates into constexpr bool result so no std::string_view array escapes the lambda.
  • Returns false when duplicates exist instead of firing an internal static_assert and always returning true:
    • rfl::Literal<...>::has_duplicates() now works as a constexpr bool predicate (returning true on duplicates instead of failing to compile).
    • Existing callers (to_ptr_named_tuple.hpp, FieldVariantParser.hpp, ParserTaggedUnion.hpp) all wrap the check in their own static_assert and now report their own domain-specific messages.
  • Added json.test_literal_has_duplicates in tests/json/test_literal.cpp covering unique/duplicate rfl::Literal (up to 32 entries) and rfl::internal::no_duplicate_field_names on empty, single, distinct, and duplicate rfl::Field tuples.

AI-authored.

@liuzicheng1987

Copy link
Copy Markdown
Collaborator

@clockblocker, this is an excellent contribution! Thank you very much! I am merging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants