diff mbox series

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

Message ID 20240601102508.878398-1-jwakely@redhat.com
State New
Headers show
Series libstdc++: Optimize std::basic_string_view::starts_with | expand

Commit Message

Jonathan Wakely June 1, 2024, 10:24 a.m. UTC
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.
---
 libstdc++-v3/include/std/string_view | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

Comments

Jonathan Wakely June 3, 2024, 3:51 p.m. UTC | #1
Pushed to trunk.

On Sat, 1 Jun 2024 at 11:26, Jonathan Wakely <jwakely@redhat.com> wrote:
>
> 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.
> ---
>  libstdc++-v3/include/std/string_view | 5 ++++-
>  1 file changed, 4 insertions(+), 1 deletion(-)
>
> diff --git a/libstdc++-v3/include/std/string_view b/libstdc++-v3/include/std/string_view
> index a7c5a126461..740aa9344f0 100644
> --- a/libstdc++-v3/include/std/string_view
> +++ b/libstdc++-v3/include/std/string_view
> @@ -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
> --
> 2.45.1
>
diff mbox series

Patch

diff --git a/libstdc++-v3/include/std/string_view b/libstdc++-v3/include/std/string_view
index a7c5a126461..740aa9344f0 100644
--- a/libstdc++-v3/include/std/string_view
+++ b/libstdc++-v3/include/std/string_view
@@ -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