https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118340

            Bug ID: 118340
           Summary: fold expression is very slow to compile when used to
                    initialize a variable
           Product: gcc
           Version: 14.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jonathan.poelen at gmail dot com
  Target Milestone: ---

The following code works perfectly, but depending on where the unfolding is
used, the compilation goes from 60 milliseconds to 2 seconds, which is
abnormal.

A sequence of 5000 values is used to show the slowdown. Tools like `time` show
a big difference with a few hundred values.

#include <utility>
#include <type_traits>

template<std::size_t... i>
static constexpr std::size_t v1 = (i + ...); // slow

template<std::size_t... i>
static constexpr std::size_t v2 = std::integral_constant<std::size_t, (i +
...)>::value; // fast

template<std::size_t... i>
static constexpr std::size_t v3 = sizeof(char[(i + ...)]); // fast

template<std::size_t... i>
constexpr int foo(std::index_sequence<i...>)
{
  return v1<i...>;  // slow 2 seconds
  // return v2<i...>;  // instant
  // return v3<i...>;  // instant
  // return (... + i); // slow 2 seconds
  // return std::integral_constant<std::size_t, (i + ...)>::value; // slow 2
seconds
  // return sizeof(char[(i + ...)]); // instant
}

int main()
{
  static_assert(12497500 == foo(std::make_index_sequence<5000>{}));
}

Reply via email to