From f5ada17eed9a095ce627c58d2a6ca2b4db2cda9b Mon Sep 17 00:00:00 2001 From: Max Podkorytov <4273004+tenpercent@users.noreply.github.com> Date: Fri, 16 Jan 2026 14:01:19 -0600 Subject: [PATCH] Replace sequence_merge O(log N) recursion with O(1) fold expression MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use operator| with fold expression (Seqs{} | ...) to merge sequences in O(1) template depth instead of O(log N) binary tree recursion. - Reduces sequence_merge instantiations from 449 to 167 (63% reduction) - Total template instantiations: 47,186 → 46,974 (-212) - ADL finds operator| since Sequence is in ck namespace --- include/ck/utility/sequence.hpp | 55 ++++++--------------------------- 1 file changed, 9 insertions(+), 46 deletions(-) diff --git a/include/ck/utility/sequence.hpp b/include/ck/utility/sequence.hpp index 1f392af070..f8d8fc6f00 100644 --- a/include/ck/utility/sequence.hpp +++ b/include/ck/utility/sequence.hpp @@ -199,57 +199,20 @@ template using make_index_sequence = typename __make_integer_seq::seq_type; -// merge sequence - optimized to avoid recursive instantiation -namespace detail { - -// Helper to concatenate multiple sequences in one step using fold expression -template -struct sequence_merge_impl; - -// Base case: single sequence -template -struct sequence_merge_impl> +// merge sequence - O(1) template depth using fold expression +// Binary merge operator for fold expression - enables O(1) depth via (S1 | S2 | S3 | ...) +// Must be in ck namespace for ADL to find it when used with Sequence types +template +constexpr Sequence operator|(Sequence, Sequence) { - using type = Sequence; -}; - -// Two sequences: direct concatenation -template -struct sequence_merge_impl, Sequence> -{ - using type = Sequence; -}; - -// Three sequences: direct concatenation (avoids one level of recursion) -template -struct sequence_merge_impl, Sequence, Sequence> -{ - using type = Sequence; -}; - -// Four sequences: direct concatenation -template -struct sequence_merge_impl, Sequence, Sequence, Sequence> -{ - using type = Sequence; -}; - -// General case: binary tree reduction (O(log N) depth instead of O(N)) -template -struct sequence_merge_impl -{ - // Merge pairs first, then recurse - using left = typename sequence_merge_impl::type; - using right = typename sequence_merge_impl::type; - using type = typename sequence_merge_impl::type; -}; - -} // namespace detail + return {}; +} template struct sequence_merge { - using type = typename detail::sequence_merge_impl::type; + // Left fold: ((S1 | S2) | S3) | ... - O(1) template depth + using type = decltype((Seqs{} | ...)); }; template <>