Skip to content

Commit 8d45e91

Browse files
committed
Improve strlen
Replace character-by-character iteration with 4-character blocks, reducing check/increment/jump operations. Prepared for future 32-bit word loading once unsigned type support is complete.
1 parent 2000ea7 commit 8d45e91

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

lib/c.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,18 @@ void abort(void);
4949

5050
int strlen(char *str)
5151
{
52+
/* process the string by checking 4 characters (a 32-bit word) at a time */
5253
int i = 0;
53-
while (str[i])
54-
i++;
55-
return i;
54+
for (;; i += 4) {
55+
if (!str[i])
56+
return i;
57+
if (!str[i + 1])
58+
return i + 1;
59+
if (!str[i + 2])
60+
return i + 2;
61+
if (!str[i + 3])
62+
return i + 3;
63+
}
5664
}
5765

5866
int strcmp(char *s1, char *s2)

0 commit comments

Comments
 (0)