[libcxx-commits] [libcxx] [libc++] Optimize std::lexicographical_compare_three_way (PR #230336)

Nikolas Klauser via libcxx-commits libcxx-commits at lists.llvm.org
Tue Oct 13 02:19:15 PDT 2026


================
@@ -50,13 +60,28 @@ _LIBCPP_HIDE_FROM_ABI constexpr auto __lexicographical_compare_three_way_fast_pa
   _Len2 __len2      = __last2 - __first2;
   _Common __min_len = std::min<_Common>(__len1, __len2);
 
-  for (_Common __i = 0; __i < __min_len; ++__i) {
-    auto __c = __comp(*__first1, *__first2);
-    if (__c != 0) {
-      return __c;
+  using _Tp = remove_pointer_t<_InputIterator1>;
+  if constexpr (is_pointer_v<_InputIterator1> && is_same_v<_InputIterator1, _InputIterator2> &&
+                __desugars_to_v<__compare_three_way_tag, _Cmp, _Tp, _Tp> && !is_volatile_v<_Tp> &&
+                __is_trivially_equality_comparable_v<_Tp, _Tp>) {
+    if constexpr (__is_trivially_lexicographically_comparable_v<_Tp, _Tp>) {
+      auto __res = std::__constexpr_memcmp(__first1, __first2, __element_count(__min_len));
+      if (__res != 0)
+        return __res <=> 0;
+    } else {
+      auto __res = std::mismatch(__first1, __last1, __first2, __last2);
+      if (__res.first != __last1 && __res.second != __last2)
+        return __comp(*__res.first, *__res.second);
----------------
philnik777 wrote:

```suggestion
        return *__res.first <=> *__res.second;
```
Since that's what we know we have anyway.

https://github.com/llvm/llvm-project/pull/230336


More information about the libcxx-commits mailing list