Skip to contentSkip to conversation

smaller strlen()

PATCH In review Alexey Dobriyan 2 participants 2 messages Aug 26, 2016

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

PATCH 1/1 smaller strlen()

gcc prefers "*s++" style code for some reason, doesn't unroll loop condition check once. Kernel strings are small but they aren't of 0 length, so that additional branch was almost never taken.

	$ ./scripts/bloat-o-meter ../vmlinux-000 ../obj/vmlinux
	strlen         30      26      -4
	strlcpy        71      64      -7
	strlcat       120      99     -21

strlcpy() and strlcat() are collateral damage :^)

---

 lib/string.c |    6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
lib/string.c +3 -3
@@ -476,11 +476,11 @@ EXPORT_SYMBOL(strim);
  */
 size_t strlen(const char *s)
 {
-	const char *sc;
+	const char *s0 = s;
 
-	for (sc = s; *sc != '\0'; ++sc)
+	while (*s++)
 		/* nothing */;
-	return sc - s;
+	return s - s0 - 1;
 }
 EXPORT_SYMBOL(strlen);
 #endif
#1 lore raw
Quoted 3 lines · Alexey Dobriyan

gcc prefers "*s++" style code for some reason, doesn't unroll loop condition check once. Kernel strings are small but they aren't of 0 length, so that additional branch was almost never taken.

Hey Alexey.

Is this gcc version specific?

And I'm confused why there isn't an asm __HAVE_ARCH_STRLEN version x86_64 strlen like x86_32 or if __builtin_strlen() is or isn't used.  Maybe Andi Kleen knows/remembers (cc'd).

Quoted 6 lines
	$ ./scripts/bloat-o-meter ../vmlinux-000 ../obj/vmlinux
	strlen         30      26      -4
	strlcpy        71      64      -7
	strlcat       120      99     -21

strlcpy() and strlcat() are collateral damage :^)