If you are asking which of methods you've posted will be faster, the only valid answer can be:
There is no way to know for sure because they are equivalent. You must profile them both and see
for yourself.
This is because the two methods are effectively the same. The do the same thing, but they use different mechanisms to do it. By the time your compiler's optimizer has finished with the code, it may have found different opportunities to increase execution speed, or it may have found opportunities in each that result in identical machine code being executed.
For example, consider:
for(std::vector<int>::iterator it = intVect.begin(); it != intVect.end(); ++i)
At first blush, it might seem like this could have a built-in inefficiency by the fact that intVect.end()
is evaluated at each loop. This would make this method slower than,
std::copy(intVect.begin(), intVect.end(), std::ostream_iterator<int>(std::cout));
...where it is only evaluated once.
However, depending on the surrounding code and your compiler's settings, it might be re-written so that it is only evaluated once, at the beginning of the for
. (Credit: @SteveJessop) Or it might even be that it isn't hoisted, but evaluating it is no different from examining a pre-computed value. It's possible that either way, the emitted code must load a pointer value from (stack pointer) + (small offset known at compile time). The only way to know for sure is to compile them both and examine the resulting assembly code.
Beyond all of this however is a more fundamental issue. You are asking which method of doing something is faster, when the core thing you're trying to do is potentially very slow to begin with, relative to the means by which you do it. If you are writing to stdout using streams, it is going to have negligible effect on the overall execution time whether you use a for
loop or std::copy
even if one is marginally faster than the other. If your concern is overall execution time, you're possibly barking up the wrong tree.