Lookup Table: Static Array vs. Stack Array
Question 8 / 51 • Correct so far: 0 (0 answered)
Constexpr Table
constexpr std::array<uint8_t, 256> makeTable() {
std::array<uint8_t, 256> t{};
for (int i = 0; i < 256; ++i)
t[i] = static_cast<uint8_t>((i * 73 + 19) & 0xFF);
return t;
}
uint8_t transform(uint8_t c) {
static constexpr auto TABLE = makeTable();
return TABLE[c];
}
uint32_t sum = 0;
for (uint8_t q : QUERIES)
sum += transform(q); Runtime Init Table
uint8_t transform(uint8_t c) {
std::array<uint8_t, 256> table;
for (int i = 0; i < 256; ++i)
table[i] = static_cast<uint8_t>((i * 73 + 19) & 0xFF);
return table[c];
}
uint32_t sum = 0;
for (uint8_t q : QUERIES)
sum += transform(q); Shared test data (shared-setup)
constexpr int kQueries = 65536;
static std::vector<uint8_t> makeQueries() {
std::vector<uint8_t> qs(kQueries);
for (int i = 0; i < kQueries; ++i)
qs[i] = static_cast<uint8_t>(i & 0xFF);
return qs;
}
static const std::vector<uint8_t> QUERIES = makeQueries(); Which snippet is faster?
Snippet A is faster. The static constexpr table lives in .rodata and is never constructed at runtime; each call is a single indexed load. Snippet B rebuilds the full 256-byte table on the stack on every call, paying that construction cost on each of the 65 536 queries.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Constexpr Table | 14.3 us | 7.7× |
| Runtime Init Table | 110 us | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.