lkml.org 
[lkml]   [2022]   [Oct]   [24]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
Patch in this message
/
From
Subject[PATCH] lib/string.c: Improve strcasecmp speed by not lowering if chars match
Date
From fcb0159ee74908f92adc34143657d8ca56e9a811 Mon Sep 17 00:00:00 2001
From: Nathan Moinvaziri <nathan@nathanm.com>
Date: Mon, 24 Oct 2022 16:37:59 -0700
Subject: [PATCH] lib/string.c: Improve strcasecmp speed by not lowering if
chars match.

With strings where many characters match exactly each character is needlessly
converted to lowercase before comparing. This patch improves the comparison
by only converting to lowercase after checking that the characters don't match.

The more characters that match exactly the better performance we expect versus
the old function.

When running tests using Quick Benchmark with two matching 256 character
strings these changes result in anywhere between ~6-9x speed improvement.

* We use unsigned char instead of int similar to strncasecmp.
* We only subtract c1 - c2 when they are not equal.

Reviewed-by: Sergey Markelov <sergio_nsk@yahoo.de>
Reviewed-by: Steve Tucker <steven.r.tucker@gmail.com>
---
lib/string.c | 17 ++++++++++++-----
1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/lib/string.c b/lib/string.c
index 3371d26a0e39..51ad56db1b5d 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -64,13 +64,20 @@ EXPORT_SYMBOL(strncasecmp);
#ifndef __HAVE_ARCH_STRCASECMP
int strcasecmp(const char *s1, const char *s2)
{
- int c1, c2;
+ /* Yes, Virginia, it had better be unsigned */
+ unsigned char c1, c2;

do {
- c1 = tolower(*s1++);
- c2 = tolower(*s2++);
- } while (c1 == c2 && c1 != 0);
- return c1 - c2;
+ c1 = *s1++;
+ c2 = *s2++;
+ if (c1 != c2) {
+ c1 = tolower(c1);
+ c2 = tolower(c2);
+ if (c1 != c2)
+ return (int)c1 - (int)c2;
+ }
+ } while (c1 != 0);
+ return 0;
}
EXPORT_SYMBOL(strcasecmp);
#endif
--
2.37.2.windows.2
\
 
 \ /
  Last update: 2022-10-25 03:50    [W:1.104 / U:0.712 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site