[libcxx-commits] [libcxx] [libc++] Optimize string operator[] for known large inputs (PR #69500)

Ilya Tocar via libcxx-commits libcxx-commits at lists.llvm.org
Wed Oct 18 12:13:57 PDT 2023


https://github.com/TocarIP created https://github.com/llvm/llvm-project/pull/69500

If we know that index is larger than SSO size, we know that we can't be in SSO case, and should access the pointer. This removes extra check from operator[] for inputs known at compile time to be larger than SSO.

>From ac053b7d3b1d5000f4d8283588ad263d4666e05e Mon Sep 17 00:00:00 2001
From: Ilya Tokar <tokarip at google.com>
Date: Fri, 6 Oct 2023 16:08:04 -0400
Subject: [PATCH] [libc++] Optimize string operator[] for known large inputs

If we know that index is larger than SSO size, we know that we
can't be in SSO case, and should access the pointer. This removes
extra check from operator[] for inputs known at compile time to be
larger than SSO.
---
 libcxx/include/string | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/libcxx/include/string b/libcxx/include/string
index 91935162f02383a..cf9f0c847eb43af 100644
--- a/libcxx/include/string
+++ b/libcxx/include/string
@@ -1198,11 +1198,17 @@ public:
 
   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 const_reference operator[](size_type __pos) const _NOEXCEPT {
     _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__pos <= size(), "string index out of bounds");
+    if (__builtin_constant_p(__pos) && !__fits_in_sso(__pos)) {
+      return *(__get_long_pointer() + __pos);
+    }
     return *(data() + __pos);
   }
 
   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 reference operator[](size_type __pos) _NOEXCEPT {
     _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__pos <= size(), "string index out of bounds");
+    if (__builtin_constant_p(__pos) && !__fits_in_sso(__pos)) {
+      return *(__get_long_pointer() + __pos);
+    }
     return *(__get_pointer() + __pos);
   }
 



More information about the libcxx-commits mailing list