Skip to content

Commit eef821e

Browse files
committed
Improve memcpy
Thie commit applies 4-byte loop unrolling and forward copy to memcpy for performance gains.
1 parent 4f35440 commit eef821e

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

lib/c.c

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,10 +121,22 @@ char *strncpy(char *dest, char *src, int len)
121121

122122
char *memcpy(char *dest, char *src, int count)
123123
{
124-
while (count > 0) {
125-
count--;
126-
dest[count] = src[count];
124+
int i = 0;
125+
126+
/* Continues as long as there are at least 4 bytes remaining to copy. */
127+
for (; i + 4 <= count; i += 4) {
128+
dest[i] = src[i];
129+
dest[i + 1] = src[i + 1];
130+
dest[i + 2] = src[i + 2];
131+
dest[i + 3] = src[i + 3];
127132
}
133+
134+
/* Ensure all @count bytes are copied, even if @count is not a multiple of
135+
* 4, or if @count was less than 4 initially.
136+
*/
137+
for (; i < count; i++)
138+
dest[i] = src[i];
139+
128140
return dest;
129141
}
130142

tests/snapshots/fib-riscv.json

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

tests/snapshots/hello-riscv.json

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

0 commit comments

Comments
 (0)