Copying a Short String into a Large Buffer: strncpy vs memcpy
Question 44 / 51 • Correct so far: 0 (0 answered)
Strncpy Copy
NOINLINE void copyString(char* buf, const char* src) {
strncpy(buf, src, kBufSize);
}
copyString(dst, kSrc); Memcpy Copy
NOINLINE void copyString(char* buf, const char* src, std::size_t len) {
memcpy(buf, src, len + 1); // +1 copies the null terminator
}
copyString(dst, kSrc, kSrcLen); Shared test data (shared-setup)
constexpr std::size_t kBufSize = 4096;
static const char kSrc[] = "hello, world!";
constexpr std::size_t kSrcLen = sizeof(kSrc) - 1; // excludes null terminator
static char dst[kBufSize]; Which snippet is faster?
Snippet B is faster. strncpy writes the source bytes then zero-pads the entire remaining buffer up to N — here that is over 4000 extra zero bytes on every call. memcpy copies only the bytes that matter (source + null terminator) and stops immediately, so its cost scales with the source length rather than the buffer size.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Memcpy Copy | 2.27 ns | 11.6× |
| Strncpy Copy | 26.2 ns | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.