Buffer Zero-Initialization: std::fill vs. memset
Question 38 / 51 • Correct so far: 0 (0 answered)
Std Fill
static void zeroBuffer(unsigned char* buf, std::size_t n) {
std::fill(buf, buf + n, static_cast<unsigned char>(0));
}
alignas(64) static unsigned char buf[kBufSize];
zeroBuffer(buf, kBufSize); Memset Zero
static void zeroBuffer(unsigned char* buf, std::size_t n) {
std::memset(buf, 0, n);
}
alignas(64) static unsigned char buf[kBufSize];
zeroBuffer(buf, kBufSize); Shared test data (shared-setup)
constexpr std::size_t kBufSize = 65536; Which snippet is faster?
Both snippets perform the same. At -O3 the compiler recognizes std::fill on a byte-like type as equivalent to memset and emits the same vectorized store sequence. The difference only appears at lower optimization levels.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Memset Zero | 396 ns | 1.0× |
| Std Fill | 396 ns | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.