libstdc++: Optimize std::basic_string_view::starts_with

We get smaller code at all optimization levels by not creating a
temporary object, just comparing lengths first and then using
traits_type::compare. This does less work than calling substr then
operator==.

libstdc++-v3/ChangeLog:

	* include/std/string_view (starts_with(basic_string_view)):
	Compare lengths first and then call traits_type::compare
	directly.
This commit is contained in:
Jonathan Wakely
2024-05-30 20:36:42 +01:00
parent 6ab5145825
commit 482f97e79f

View File

@@ -385,7 +385,10 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
[[nodiscard]]
constexpr bool
starts_with(basic_string_view __x) const noexcept
{ return this->substr(0, __x.size()) == __x; }
{
return _M_len >= __x._M_len
&& traits_type::compare(_M_str, __x._M_str, __x._M_len) == 0;
}
[[nodiscard]]
constexpr bool