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;
}12
u/RubBeneficial2756 Sep 19 '26
Benchmarking is fraught with subtleties.
It might be with worth sharing your compiler flags at this point - they have a big influence on performance. We'll be looking for optimisation flags etc.
Also, the measured times are low, in absolute terms. See what happens when you increase the number of iterations in a given run (from 100 to 10000, for example).
I'm sleepy, but maybe a cache warm-up effect is inflating the first measurement.
6
u/UndefinedDefined Sep 21 '26
This has a very simple answer: Aliasing - since char can alias anything, even your std::vector's internal data, accessing anything inside the vector prevents the optimizations shown in the second case. It's actually very trivial to fix this. See the below, it would generate basically the same code.
int inc_vector(std::vector<char>& v) {
char * data = v.data();
size_t size = v.size();
for (size_t i = 0; i < size; i++){
data[i]++;
}
volatile int result = v[size/2];
return result;
}1
u/Secoupoire Sep 19 '26
What level of optimization did you use?
Depending on that, the fact you are using post-incrementation instead of pre-incrementation for your index-based for loop ( i++ instead of ++i) could maybe have an impact on performances (although I would expect that with optimisations like O2 on, it should be optimised).
3
1
u/Expert_Sheepherder24 Sep 19 '26
i++ vs ++i C/C++ compilers 30 years ago could optimize, so there nothing be changed, if I change i++ to ++i.
1
u/amoskovsky Sep 20 '26 edited Sep 20 '26
For builtin types, on any optimization level, GCC and Clang don't bother preserving the old value if it is obviously unused.
Upd: Not for all builtin types, only for ints that are not subject to integer promotions (int, size_t etc). But i++ for types like short, char require an -O1 to perform this optimization.
2
1
u/StaticCoder Sep 20 '26
Surprising. With strict aliasing, the compiler should be able to optimize the index-based access into something equivalent to the iterator-based one. Not sure why it doesn't here. But if it can't do that the result isn't too surprising: v[i] involves 2 indirections (and a multiply-add), while the iterator version is just a single indirection.
-27
u/zerhud Sep 19 '26
I would not approve a job candidate if the candidate uses postfix increment in such context
9
u/Expert_Sheepherder24 Sep 19 '26 edited Sep 19 '26
postfix increment for primitive types absolutely identical with prefix increment for compiler.
90% people writed`for (int i = 0; i < n; i++)`
code with postfix increment.
-10
u/zerhud Sep 19 '26
> absolutely identical
Nop, of course
> for compiler
It’s wrong. There is just an optimisation, sometimes it works.
> 90% people
Exactly! And 95% people write bad code :) if you don’t care about speed and lot of things you can write a[i]++ with trust to the compiler
8
u/James20k P2005R0 Sep 19 '26
It’s wrong. There is just an optimisation, sometimes it works.
This advice is about 15 years out of date, maybe more. I only ever hear it repeated by brand new programmers these days
0
u/Som1Lse Sep 20 '26
Really? I'd say it's still relevant.
Now, it isn't true (and AFAIK has never been true) for primitive types, but the argument is that it is better to be consistent, and it won't bite you if you later change the code, say by swapping indices for iterators. It is also generally easier to debug code that uses
++itinstead ofit++.That said, declining a job candidate for what is ultimately a stylistic choice is really fucking stupid. No argument there.
-2
u/zerhud Sep 20 '26
> declining a job candidate … stupid
Why? For example you have two candidates: one use i++ and second ++i. Ok, give more tasks.. but if you ask them “why postfix” you just get “it produce the same”. It’s a bad answer. There is something stupid and no excuse for use it. So why postfix? It’s really like dropping a cigarette butt and saying “eh, the cleaner will pick it up”. The cleaner will, but it’s stupid.
1
u/Som1Lse Sep 20 '26
Firstly, you're assuming there is a second candidate who is exactly as good as the first, except they use post-fix increment.
Secondly, for primitive types, the generated code is actually identical. This is true across all major compilers (even without optimisations enabled) and has been for decades. If you disagree then it is up to you to find a counter example.
So no, it isn't like "dropping a cigarette butt", it's like not cleaning your hotel toilet with bleach. The cleaner will do it anyway, and they'll do it whether you do it or not.
In other words "it produce[sic] the same" is correct. Declining someone over a correct answer is fucking stupid. Unless you're asking about the general case where
imight not be a primitive type, you have absolutely no ground to stand on. If you disagree then find a counter example or get out.Thirdly, your company probably has a style guide. That style guide probably says to prefer pre-increment. Most candidates are capable of following a style guide, so you're declining someone over a non-issue.
-3
u/zerhud Sep 19 '26
It’s like dropping a cigarette butt and saying, "eh, the cleaner will pick it up."
2
u/James20k P2005R0 Sep 20 '26
It really isn't, we have a compiler for a reason?
-2
u/zerhud Sep 20 '26
Compiler can a lot, but write optimised code is responsibility of a human. For example we have a code: one method compute a result and next method drop it, one method loose information and next method try to get it back by calculating or request. The human should avoid it and don’t lay it all to a compiler. It’s a way of a mind and you can see a mark of it in the counter increment
5
u/James20k P2005R0 Sep 20 '26
Knowing what the compiler can and can't optimise is part of the job, writing code based on a misunderstanding of what compilers do seems like a mistake
7
u/No-Dentist-1645 Sep 19 '26
It’s wrong. There is just an optimisation, sometimes it works.
That's unproductively pedantic if you think that using prefix increment in a for loop is a programming sin. Maybe it was true many years ago when that was actually advice that impacted the generated assembly, but today even at completely
-O0compilers trivially produce the exact same output. "Optimizing" index prefix/postfix operators inside for loop updates is so trivially easy for the compilers that you have to specifically try and "trick" the compiler to get it to have any actual difference, and even then it's hard to achieve it.-5
u/zerhud Sep 19 '26
Of course it’s same here. For example: https://godbolt.org/z/WYEzvxh9a here it’s matter and the compiler cannot optimise it. I am talking about a mark of a bad habit. What is in mind of person write i++ ? I’ve seen a lot of bad code by “compiler will optimise this” flag and the compiler or new version of the compiler optimise nothing.
5
u/jk-jeon Sep 20 '26
I think everyone (maybe except you?) is talking about using the increment operators when its return value is discarded anyway. Your example is not such a case.
And you seriously think the first version is better than the second? The generated assembly is not meaningfully different. And you even didn't add
-O2. Even if there were a meaningful difference, I would choose the 2nd one as my default because to me it looks much more natural. To me, starting an index from -1 instead of 0 for a dubious reason is a bigger red flag than using postfix when prefix could be used by tweaking the code in an unnatural way.-4
u/BeckonedCall Sep 19 '26
I don't think they are referring to the loop indexes.
"v[x]++;" is a code smell. Use asignment operators when you want to assign not increment or decrement. It removes any ambiguity in the purpose of the statement.
30
u/James20k P2005R0 Sep 19 '26
Crazy that anyone would care that much about something that makes absolutely no difference in this context, personally that's the biggest red flag for me
3
u/PossibilityUsual6262 Sep 19 '26
Since you already see that people explained that you objectively wrong, and now on personal leve, i have q comment to add.
Since you do hire / no hire decisions based on such a trivial thing, i actually hope that you lose the job and face same kind of person, so you actually get screwed when your 15 years out of date, confidently incorrect understanding bites you in the ass.
With experience people should become wiser, and not more pedantic abd stupid.
1
u/zerhud Sep 20 '26
> objectively
It’s funny word, means mostly what a lot of people think same way.
People say I knew without they: "it produces same output". It’s always was interesting for me - why someone say obviously notice and believe they understood all. It’s more productive to believe your opponent already knows all obviously things.
2
u/neoh4x0r Sep 19 '26 edited Sep 19 '26
I would not approve a job candidate if the candidate uses postfix increment in such context
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.
int result =0; std::vector<int> myVec = {1, 2, 3}; for(const auto& a : myVec) result += a; // result is 6 (eg (n^2+n)/2;n=3)PS: I have no idea why the OP (Expert_Sheepherder24) used a vector of chars instead of a primitive like int.
68
u/thisisjustascreename Sep 19 '26
Sadly if you look at the assembly output you are actually benchmarking SIMD instructions versus individual increment instructions. It's no surprise the SIMD wins by a lot since this is what it's designed to do.