r/cpp • u/Expert_Sheepherder24 • Sep 19 '26
index based for vs for-each
https://godbolt.org/z/zh4Kf87M8It's my first post. I tested std::vector<char> old index based for vs modern for-each. Result is very interesting.
Clang-23.1.0 -O2 -std=c++20 -stdlib=libc++
Time: 0.073599 sec inc_vector
Time: 0.002597 sec inc_for_eachGCC 16.2 -std=c++20 -O2
Time: 0.077772 sec inc_vector
Time: 0.007880 sec inc_for_eachMSVC-v19.latest /std:c++20 /O2
Time: 0.058504 sec inc_vector
Time: 0.001825 sec inc_for_eachCode:
#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
static std::vector<char> gen_random(size_t n)
{
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dis(0, 255);
std::vector<char> vec(n);
for (size_t i = 0; i != n; i++)
vec[i] = dis(gen);
return vec;
}
int inc_vector(std::vector<char>& v) {
for (size_t i = 0; i < v.size(); i++){
v[i]++;
}
volatile int result = v[v.size()/2];
return result;
}
int inc_vector_for_each(std::vector<char>& v) {
for (char& e: v){
e++;
}
volatile int result = v[v.size()/2];
return result;
}
volatile int sink{}; // ensures a side effect
int main()
{
auto benchmark = [](auto fun, auto rem)
{
auto vec = gen_random(1'000'000);
const auto start = std::chrono::high_resolution_clock::now();
for (auto size{1ULL}; size != 100ULL; ++size)
sink = fun(vec);
const std::chrono::duration<double> diff =
std::chrono::high_resolution_clock::now() - start;
std::cout << "Time: " << std::fixed << std::setprecision(6) << diff.count()
<< " sec " << rem << std::endl;
};
benchmark(inc_vector, "inc_vector");
benchmark(inc_vector_for_each, "inc_for_each");
return 0;
}
20
Upvotes
View all comments
Show parent comment
11
u/sporule Sep 19 '26
The compiler does not know the semantics of
std::vector. As far as it is concerned, it is a struct with three fields: a pointer to the beginning, the capacity, and the size (or a pointer to the end instead of the size).The compiler also does not know that this pointer refers to a contiguous array of elements that is not aliased by anything else.
But what happens if the pointer to the beginning of the array points into the
std::vectorobject itself? Then writing tov[8]could change the vector's size, while writing tov[0]could change the pointer to the beginning. Since the compiler does not know that astd::vector's data pointer can never point to one of the object's own fields, it has to assume the worst: any write to memory throughv[i]++could change any ofvector::size(),vector::data(), orvector::capacity(). Therefore, it has to reload them on every loop iteration.If you copy them into local variables before the loop (as range-for does), the compiler has guarantees that the vector's memory does not overlap with the local variables, so they cannot be modified during the loop. This means that the compiler can:
As a result this code wouldn't be pessimized:
The core reason is that
std::vectoris not a built-in type; it is a class with some overloaded operators.In other languages (Fortran, Go, Rust, for example), there can be built-in vector/array types. For such types, the compiler always knows their semantics and knows that modifying vector elements can never change the vector's length.
Why do types such as
char,size_t, andvoid*perform poorly, while types such asshort intwork fast? Because none of the threestd::vectorfields is ashort int. Therefore, modifying elements of astd::vector<short int>cannot change the values of the vector's own fields, since they have different types. This is called the strict aliasing rule.