Skip to content

Commit 06f2e89

Browse files
committed
Improve strlen
The original loop had to check, increment, and jump for every single character. The new loop does this for every 4 characters. It can load a full 32-bit word directly once 'unsigned' is implemented properly later.
1 parent 6ef2402 commit 06f2e89

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

lib/c.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,17 @@ void abort(void);
5050
int strlen(char *str)
5151
{
5252
int i = 0;
53-
while (str[i])
54-
i++;
55-
return i;
53+
/* process the string by checking 4 characters (a 32-bit word) at a time */
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)

tests/snapshots/fib-arm.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

tests/snapshots/hello-arm.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)