Large Stack Buffer: Zero-Initialized vs Uninitialized
Question 51 / 51 • Correct so far: 0 (0 answered)
Zero Init Buf
NOINLINE std::size_t buildMessage(int value) {
char buf[kBufSize]{};
std::snprintf(buf, kBufSize, "result=%d status=ok timestamp=12345", value);
return std::strlen(buf);
}
std::size_t len = buildMessage(kValue); No Init Buf
NOINLINE std::size_t buildMessage(int value) {
char buf[kBufSize];
std::snprintf(buf, kBufSize, "result=%d status=ok timestamp=12345", value);
return std::strlen(buf);
}
std::size_t len = buildMessage(kValue); Shared test data (shared-setup)
constexpr std::size_t kBufSize = 16 * 1024;
constexpr int kValue = 42; Which snippet is faster?
Snippet B is faster. char buf[kBufSize]{} looks like defensive coding but
the compiler emits a full memset of the entire buffer on every call — here
over 16 KB — before snprintf writes its ~30 bytes. Snippet B skips that
redundant pass: snprintf supplies all the initialisation that is actually
needed. The zero-init cost scales with the buffer size, not with how much
you write into it.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| No Init Buf | 23.8 ns | 5.3× |
| Zero Init Buf | 126 ns | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.