[libcxx-commits] [libcxx] [libc++] optimization on ranges::drop_view::begin (#72883) (PR #72929)

Hongyu Ouyang via libcxx-commits libcxx-commits at lists.llvm.org
Mon Nov 20 16:40:32 PST 2023


https://github.com/casavaca created https://github.com/llvm/llvm-project/pull/72929

as pointed out from the github issue #72883 :
> ... the implementation only needs to return the value of ranges::next
  and does not need to obtain the value through ranges::advance, which will have
  O(n) complexity in the case of random-access-sized but non-common range.

>From ae09b387d712307c42be0ac14225bb718e6db5be Mon Sep 17 00:00:00 2001
From: Hongyu Ouyang <HongyuOuyang at proton.me>
Date: Mon, 20 Nov 2023 16:34:10 -0800
Subject: [PATCH] [libc++] optimization on ranges::drop_view::begin (#72883)

as pointed out from the github issue:
> ... the implementation only needs to return the value of ranges::next
  and does not need to obtain the value through ranges::advance, which will have
  O(n) complexity in the case of random-access-sized but non-common range.
---
 libcxx/include/__ranges/drop_view.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/libcxx/include/__ranges/drop_view.h b/libcxx/include/__ranges/drop_view.h
index f10476f0011e739..2557d030fd61145 100644
--- a/libcxx/include/__ranges/drop_view.h
+++ b/libcxx/include/__ranges/drop_view.h
@@ -104,7 +104,8 @@ namespace ranges {
     constexpr auto begin() const
       requires random_access_range<const _View> && sized_range<const _View>
     {
-      return ranges::next(ranges::begin(__base_), __count_, ranges::end(__base_));
+      auto __dist = ranges::distance(__base_);
+      return ranges::begin(__base_) + std::min<range_difference_t<_View>>(__count_, __dist);
     }
 
     _LIBCPP_HIDE_FROM_ABI



More information about the libcxx-commits mailing list