Which is better?
for (auto anItem = aVector.begin(), endVector = aVector.end(); anItem != endVector ; ++anItem )
or
for (auto anItem = aVector.begin(), anItem != aVector.end(); ++anItem )
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I always use second – the simpler one.
I believe you expect that first could be faster, but typical implementation of std::vector::end() is to return simple pointer pointing to first element after the last one in vector, so effectively there is not performance improvement in second case because end() is always inline function. Maybe it could be performance improvement when you store current end() in
const iteratorlike this:But this loop and your first loop is less safe in many cases than your second loop. That is why I see almost always second loop.
[UPDATE]
I do not believe that first loop has any advantage over the second when talking about performance. Modern compilers can detect that aVector.end() result is not changing through entire loop so they are free to optimize. The only performance advantage of first loop could be case when aVector changes in loop – but this results in wrong behavior.
So, from whatever side to look at this question – the second loop is always better.
[UPDATE2]
Just to check it. I wrote two functions like this:
And compiled them to assembler
g++ -O3 -S. There is no difference in assembler code on my computer/compiler – however this does not mean they wouldn’t be any differences in all cases.