Course contentsShow
← C
Lesson 860 of 1,21912. The Standard LibraryFree lesson

Performance differences between `str` and `mem` functions

Performance differences between str and mem functions

What you'll learn: Why knowing the size of your data beforehand makes mem functions significantly faster than their str counterparts.

In C, you often have two ways to do the same thing. To copy data, you can use strcpy or memcpy. To compare data, you use strcmp or memcmp. While they seem interchangeable, they work very differently under the hood.

The Stop Sign vs. The Tape Measure

Imagine you are a worker tasked with moving boxes from one room to another.

Using a str function (like strcpy) is like moving boxes without knowing how many there are. You must pick up a box, look inside to see if it’s empty (the \0 null terminator), and if not, move it and repeat. You are constantly stopping to check for that "end of string" signal. This checking adds overhead to every single byte you process.

Using a mem function (like memcpy) is like being told exactly how many boxes to move. Because you know the count (the n argument), you don't have to look inside the boxes. You can grab a stack of four boxes at once and sprint.

Why mem Wins

Modern CPUs are designed to process large chunks of data at once. Because mem functions know the exact size of the buffer, the compiler and the CPU can perform "vectorization"—processing 16, 32, or even 64 bytes in a single clock cycle.

str functions cannot easily do this because they might hit the null terminator at any moment. They generally have to check bytes one by one, which prevents the CPU from reaching top speed.

#include <string.h>

void example(char *dest, const char *src, size_t len) {
    // SLOWER: Scans every byte looking for '\0'
    strcpy(dest, src); 

    // FASTER: Directly moves 'len' bytes without checking content
    // Works best when you already tracked the length!
    memcpy(dest, src, len);
}

When to Use Which?

Use str functions when you are working with traditional, null-terminated strings where the length is unknown. However, if you already know the length of your data—perhaps you just calculated it or you're working with a fixed-size buffer—always reach for the mem functions. They are almost always the fastest path through memory.

Key takeaway

mem functions outperform str functions because they skip the "null-terminator check" and allow the CPU to move data in large, optimized chunks.