Skip to content

Commit 38595fb

Browse files
authored
[libc++] Remove a few unnecessary branches from basic_string::find (#137266)
I've recently looked at the assembly for `basic_string::find()` and realized that there were a few branches I didn't expect. It turns out that we check for null before calling `__constexpr_memchr` in some cases, which the compiler doesn't optimize away. This is a really uncommon case though, so I'm not convinced it makes a ton of sense to optimize for that. The second case is where `__pos >= __sz`. There, we can instead check `__pos > __sz`, which the optimizer is able to remove if `__pos == 0`, which is also a quite common case (basic_string::find(CharT), without an explicit size parameter).
1 parent 7d98b66 commit 38595fb

File tree

1 file changed

+1
-5
lines changed

1 file changed

+1
-5
lines changed

libcxx/include/__string/char_traits.h

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,6 @@ struct char_traits<char> {
132132

133133
static _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 const char_type*
134134
find(const char_type* __s, size_t __n, const char_type& __a) _NOEXCEPT {
135-
if (__n == 0)
136-
return nullptr;
137135
return std::__constexpr_memchr(__s, __a, __n);
138136
}
139137

@@ -250,8 +248,6 @@ struct char_traits<wchar_t> : __char_traits_base<wchar_t, wint_t, static_cast<wi
250248

251249
static _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 const char_type*
252250
find(const char_type* __s, size_t __n, const char_type& __a) _NOEXCEPT {
253-
if (__n == 0)
254-
return nullptr;
255251
return std::__constexpr_wmemchr(__s, __a, __n);
256252
}
257253
};
@@ -352,7 +348,7 @@ inline _LIBCPP_CONSTEXPR_SINCE_CXX17 size_t char_traits<char32_t>::length(const
352348
template <class _CharT, class _SizeT, class _Traits, _SizeT __npos>
353349
inline _SizeT _LIBCPP_CONSTEXPR_SINCE_CXX14 _LIBCPP_HIDE_FROM_ABI
354350
__str_find(const _CharT* __p, _SizeT __sz, _CharT __c, _SizeT __pos) _NOEXCEPT {
355-
if (__pos >= __sz)
351+
if (__pos > __sz)
356352
return __npos;
357353
const _CharT* __r = _Traits::find(__p + __pos, __sz - __pos, __c);
358354
if (__r == nullptr)

0 commit comments

Comments
 (0)