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
2
u/neoh4x0r Sep 19 '26 edited Sep 19 '26
There's no noticeable performance impact between using pre/postfix with primitive types (eg. integer or size_t).
The only time it would matter, to use ++i (prefix), is if you wanted to avoid making copies.
Then again you could avoid it altogether by doing the following, and for simply getting the sum of vector elements, an array index isn't needed.
PS: I have no idea why the OP (Expert_Sheepherder24) used a vector of chars instead of a primitive like int.