[libcxx-commits] [libcxx] [libc++] Optimize make_heap() and sift_down() (PR #121480)

Yang Kun via libcxx-commits libcxx-commits at lists.llvm.org
Fri Jan 3 01:36:03 PST 2025


================
@@ -29,54 +29,37 @@ _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 void
 __sift_down(_RandomAccessIterator __first,
             _Compare&& __comp,
             typename iterator_traits<_RandomAccessIterator>::difference_type __len,
-            _RandomAccessIterator __start) {
+            typename iterator_traits<_RandomAccessIterator>::difference_type __start) {
   using _Ops = _IterOps<_AlgPolicy>;
 
   typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
   typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-  // left-child of __start is at 2 * __start + 1
-  // right-child of __start is at 2 * __start + 2
-  difference_type __child = __start - __first;
-
-  if (__len < 2 || (__len - 2) / 2 < __child)
-    return;
-
-  __child                         = 2 * __child + 1;
-  _RandomAccessIterator __child_i = __first + __child;
-
-  if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + difference_type(1)))) {
-    // right-child exists and is greater than left-child
-    ++__child_i;
-    ++__child;
-  }
-
-  // check if we are in heap-order
-  if (__comp(*__child_i, *__start))
-    // we are, __start is larger than its largest child
-    return;
-
-  value_type __top(_Ops::__iter_move(__start));
-  do {
-    // we are not in heap-order, swap the parent with its largest child
-    *__start = _Ops::__iter_move(__child_i);
-    __start  = __child_i;
-
-    if ((__len - 2) / 2 < __child)
-      break;
 
-    // recompute the child based off of the updated parent
-    __child   = 2 * __child + 1;
-    __child_i = __first + __child;
+  _LIBCPP_ASSERT_INTERNAL(__len >= 2, "shouldn't be called unless __len >= 2");
 
-    if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + difference_type(1)))) {
-      // right-child exists and is greater than left-child
-      ++__child_i;
-      ++__child;
+  value_type __top(_Ops::__iter_move(__first + __start));
+  // left-child of __start is at 2 * __start + 1
+  // right-child of __start is at __child_i + 1
+  for (difference_type __child; (__child = 2 * __start + 1) < __len;) {
----------------
omikrun wrote:

> Why? This is horrible to read.

Oh, okay.

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


More information about the libcxx-commits mailing list