public inbox for libc-alpha@sourceware.org
 help / color / mirror / Atom feed
* [PATCH] Avoid double bounds check at the start of the loop
@ 2023-09-06 10:58 Wilco Dijkstra
  0 siblings, 0 replies; 2+ messages in thread
From: Wilco Dijkstra @ 2023-09-06 10:58 UTC (permalink / raw)
  To: tirtajames45; +Cc: 'GNU C Library'

Hi James,

So the change you're proposing is correct, but did you benchmark it?
The code is written like it is for a good reason: the checks at the start of
the loop avoid one taken branch per loop iteration. So eventhough there
is an unnecessary branch in the very first iteration, performance actually
improves significantly by doing it this way.

Cheers,
Wilco

^ permalink raw reply	[flat|nested] 2+ messages in thread

* [PATCH] Avoid double bounds check at the start of the loop
@ 2023-09-04 14:56 James Tirta Halim
  0 siblings, 0 replies; 2+ messages in thread
From: James Tirta Halim @ 2023-09-04 14:56 UTC (permalink / raw)
  To: libc-alpha; +Cc: James Tirta Halim

---
 string/memmem.c | 4 ++--
 string/strstr.c | 2 ++
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/string/memmem.c b/string/memmem.c
index 13df3bcdd4..dea3e5a29c 100644
--- a/string/memmem.c
+++ b/string/memmem.c
@@ -92,7 +92,7 @@ __memmem (const void *haystack, size_t hs_len,
   shift1 = m1 - shift[hash2 (ne + m1)];
   shift[hash2 (ne + m1)] = m1;
 
-  for ( ; hs <= end; )
+  do
     {
       /* Skip past character pairs not in the needle.  */
       do
@@ -121,7 +121,7 @@ __memmem (const void *haystack, size_t hs_len,
 
       /* Skip based on matching the hash of the needle end.  */
       hs += shift1;
-    }
+    } while (hs <= end);
   return NULL;
 }
 libc_hidden_def (__memmem)
diff --git a/string/strstr.c b/string/strstr.c
index 23618e2eb2..7ec812b931 100644
--- a/string/strstr.c
+++ b/string/strstr.c
@@ -121,6 +121,7 @@ STRSTR (const char *haystack, const char *needle)
   shift1 = m1 - shift[hash2 (ne + m1)];
   shift[hash2 (ne + m1)] = m1;
 
+  goto start;
   while (1)
     {
       if (__glibc_unlikely (hs > end))
@@ -130,6 +131,7 @@ STRSTR (const char *haystack, const char *needle)
 	    return NULL;
 	}
 
+start:
       /* Skip past character pairs not in the needle.  */
       do
 	{
-- 
2.42.0


^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2023-09-06 10:58 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-09-06 10:58 [PATCH] Avoid double bounds check at the start of the loop Wilco Dijkstra
  -- strict thread matches above, loose matches on Subject: below --
2023-09-04 14:56 James Tirta Halim

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).