Skip to content

Commit cc3f6cd

Browse files
Speed up compilation of std::visit() by ~8x by hard-coding the most common cases
1 parent b9e2f7a commit cc3f6cd

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

libcxx/include/variant

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1578,11 +1578,42 @@ _LIBCPP_HIDE_FROM_ABI constexpr void __throw_if_valueless(_Vs&&... __vs) {
15781578
}
15791579
}
15801580

1581-
template < class _Visitor, class... _Vs, typename>
1581+
template <class _Visitor, class... _Vs, typename>
15821582
_LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) visit(_Visitor&& __visitor, _Vs&&... __vs) {
1583-
using __variant_detail::__visitation::__variant;
1584-
std::__throw_if_valueless(std::forward<_Vs>(__vs)...);
1585-
return __variant::__visit_value(std::forward<_Visitor>(__visitor), std::forward<_Vs>(__vs)...);
1583+
# define _XDispatchIndex(_I) \
1584+
case _I: \
1585+
if constexpr (__variant_size::value > _I) { \
1586+
return __visitor(__variant::__get_alt<_I>(std::forward<_Vs>(__vs)...).__value); \
1587+
} \
1588+
[[__fallthrough__]]
1589+
# define _XDispatchMax 7 // Speed up compilation for the common cases
1590+
if constexpr (sizeof...(_Vs) == 1) {
1591+
if constexpr (variant_size<__remove_cvref_t<_Vs>...>::value <= _XDispatchMax) {
1592+
using __variant_detail::__access::__variant;
1593+
using __variant_size = variant_size<__remove_cvref_t<_Vs>...>;
1594+
const size_t __indexes[] = {__vs.index()...};
1595+
switch (__indexes[0]) {
1596+
_XDispatchIndex(_XDispatchMax - 7);
1597+
_XDispatchIndex(_XDispatchMax - 6);
1598+
_XDispatchIndex(_XDispatchMax - 5);
1599+
_XDispatchIndex(_XDispatchMax - 4);
1600+
_XDispatchIndex(_XDispatchMax - 3);
1601+
_XDispatchIndex(_XDispatchMax - 2);
1602+
_XDispatchIndex(_XDispatchMax - 1);
1603+
_XDispatchIndex(_XDispatchMax - 0);
1604+
default:
1605+
__throw_bad_variant_access();
1606+
}
1607+
} else {
1608+
static_assert(variant_size<__remove_cvref_t<_Vs>...>::value > _XDispatchMax, "forgot to add dispatch case");
1609+
}
1610+
} else {
1611+
using __variant_detail::__visitation::__variant;
1612+
std::__throw_if_valueless(std::forward<_Vs>(__vs)...);
1613+
return __variant::__visit_value(std::forward<_Visitor>(__visitor), std::forward<_Vs>(__vs)...);
1614+
}
1615+
# undef _XDispatchMax
1616+
# undef _XDispatchIndex
15861617
}
15871618

15881619
# if _LIBCPP_STD_VER >= 20

0 commit comments

Comments
 (0)