Buffer Allocation: Heap Buffer vs Stack Buffer
Question 37 / 51 • Correct so far: 0 (0 answered)
Heap Buffer
void processBuffer(int seed) {
auto buf = std::make_unique<std::uint8_t[]>(kBufSize);
for (std::size_t i = 0; i < kBufSize; ++i)
buf[i] = static_cast<std::uint8_t>((seed + i) & 0xFF);
benchmark::DoNotOptimize(buf[kBufSize - 1]);
}
processBuffer(kSeed); Stack Buffer
void processBuffer(int seed) {
std::uint8_t buf[kBufSize];
for (std::size_t i = 0; i < kBufSize; ++i)
buf[i] = static_cast<std::uint8_t>((seed + i) & 0xFF);
benchmark::DoNotOptimize(buf[kBufSize - 1]);
}
processBuffer(kSeed); Shared test data (shared-setup)
constexpr std::size_t kBufSize = 256;
constexpr int kSeed = 42; Which snippet is faster?
Snippet B is faster. Heap allocation/deallocation goes through the allocator, while a fixed-size stack array is created with simple stack-pointer movement. For small temporary buffers, that lower setup cost usually wins.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Heap Buffer | 8.86 ns | 1.0× |
| Stack Buffer | 1.5 ns | 5.9× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.