Skip to contentSkip to conversation

lib/string.c: make strncmp() smaller

PATCH In review Alexey Dobriyan 2 participants 3 messages Feb 8, 2019 – Feb 9, 2019

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 lib/string.c: make strncmp() smaller

Space savings on x86_64:

add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-29 (-29)
Function old new delta
strncmp 67 38 -29

Space savings on arm:

add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-60 (-60)
Function old new delta
strncmp 116 56 -60

---

 lib/string.c |   10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
lib/string.c +4 -6
@@ -344,16 +344,14 @@ EXPORT_SYMBOL(strcmp);
  */
 int strncmp(const char *cs, const char *ct, size_t count)
 {
-	unsigned char c1, c2;
+	while (count--) {
+		unsigned int c1 = *(unsigned char *)cs++;
+		unsigned int c2 = *(unsigned char *)ct++;
 
-	while (count) {
-		c1 = *cs++;
-		c2 = *ct++;
 		if (c1 != c2)
-			return c1 < c2 ? -1 : 1;
+			return c1 - c2;
 		if (!c1)
 			break;
-		count--;
 	}
 	return 0;
 }
#1 lore raw
Quoted 11 lines · Alexey Dobriyan

Space savings on x86_64:

add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-29 (-29)
Function old new delta
strncmp 67 38 -29

Space savings on arm:

add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-60 (-60)
Function old new delta
strncmp 116 56 -60

[]

Quoted 7 lines
lib/string.c +0 -1
@@ -344,16 +344,14 @@ EXPORT_SYMBOL(strcmp);
  */
 int strncmp(const char *cs, const char *ct, size_t count)
 {
-	unsigned char c1, c2;

lib/string.c EXPORT_SYMBOL(strcmp); · line 352

Quoted 10 lines
lib/string.c +4 -4
+	while (count--) {
+		unsigned int c1 = *(unsigned char *)cs++;
+		unsigned int c2 = *(unsigned char *)ct++;
 
-	while (count) {
-		c1 = *cs++;
-		c2 = *ct++;
 		if (c1 != c2)
-			return c1 < c2 ? -1 : 1;
+			return c1 - c2;

This does change the return value for most comparisons.

Wasn't there a specific reason for -1 and 1?

#2 lore raw
Quoted 6 lines · Joe Perches

lib/string.c EXPORT_SYMBOL(strcmp); · line 352

Quoted 2 lines · Alexey Dobriyan
lib/string.c +1 -1
-			return c1 < c2 ? -1 : 1;
+			return c1 - c2;

This does change the return value for most comparisons.

It does.

Quoted 1 line

Wasn't there a specific reason for -1 and 1?

Maybe. Spec says anything positive or negative works.