Container Iteration: std::list vs std::vector
Question 16 / 51 • Correct so far: 0 (0 answered)
List Sum
long long sumElements(const std::list<int>& data) {
long long total = 0;
for (int v : data)
total += v;
return total;
}
long long result = sumElements(DATA_LIST); Vector Sum
long long sumElements(const std::vector<int>& data) {
long long total = 0;
for (int v : data)
total += v;
return total;
}
long long result = sumElements(DATA_VEC); Shared test data (shared-setup)
constexpr int kElementCount = 65536;
static std::list<int> makeList() {
std::list<int> l;
for (int i = 0; i < kElementCount; ++i)
l.push_back(i);
return l;
}
static std::vector<int> makeVec() {
std::vector<int> v(kElementCount);
std::iota(v.begin(), v.end(), 0);
return v;
}
static const std::list<int> DATA_LIST = makeList();
static const std::vector<int> DATA_VEC = makeVec(); Which snippet is faster?
Snippet B is faster. std::vector stores elements contiguously, so the hardware prefetcher can stream them efficiently. std::list stores each element in a separately heap-allocated node; following the next pointer on every step causes a random cache miss that dominates iteration time.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| List Sum | 55.1 us | 1.0× |
| Vector Sum | 1.85 us | 29.7× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.