For example, I want to print vector's content. What will be executed faster, the "traditional for" cycle(1), or the C++11 one(2)? Or there is no speed difference at all? Any information is appreciated.
1)
for (int i=0;i<FooBar_vector.size();i++)
{
cout<<FooBar_vector[i]<<endl;
}
2)
for (auto &val : FooBar_vector)
{
cout<< val <<endl;
}
There are no fundamental reasons why a ranged-based for loop would be slower than a manual loop. The code that a ranged-based for loop is defined to be identical to is a relatively optimal loop.
In your case, each loop iteration logically calls size()
. If at any point in the loop the compiler becomes unable to prove that size()
cannot change in your loop, the compiler must actually call size()
(which typically involves subtracting two pointers) and check it. This could cost some performance in your manual loop case.
In the for(:)
loop it could cost correctness, in that if the vector being looped over has its begin or end iterator (or current iterator) invalidated during the loop, the loop continues to loop over the old iterators and undefined behavior can result.
So the two loops are not (in general) equivalent.
In the cases where the looped-over range is unchanging, the for(:)
loop will perform as well, or better, than most hand-crafted loops that just iterate over elements, because most hand-crafted loops don't make a copy of end()
and compare against that copy.
In this particular case, the overhead of IO (and to a lesser extent, formatting) will massively overwhelm any loop overhead.