If your compiler optimises your code, it doesn't matter which one you use. Otherwise, you might want to use the more OOP-looking format: numbers.begin()
This code has been plugged into Quick Bench for speed measurement:
std::vector<int> arr = {0,1,2};
static void formatA(benchmark::State& state) {
for (auto _ : state) { // Code inside this loop is measured repeatedly
std::vector<int>::iterator itrA = arr.begin(); // arr.end();
benchmark::DoNotOptimize(itrA);
}
}
// Register the function as a benchmark
BENCHMARK(formatA);
static void formatB(benchmark::State& state) {
for (auto _ : state) { // Code before the loop is not measured
std::vector<int>::iterator itrB = begin(arr); // end(arr);
benchmark::DoNotOptimize(itrB);
}
}
BENCHMARK(formatB);
All compiled using STL=libstdc++ (GNU), results for begin()
are as follows:
Whereas for end()
:
Without optimisation,
formatA callq
s <std::vector<int, std::allocator<int> >::begin()>
and end()
respectively, while
formatB callq
s <decltype (({parm#1}.begin)()) std::begin<std::vector<int, std::allocator<int> > >(std::vector<int, std::allocator<int> >&)>
and end()
respectively also. Time will be lost by deducing data type for formatB.
WITH optimisation, the compiler has already done the deducing, both will be using the following assembly and varies nothing else other than addresses:
mov 0x3c5b1(%rip),%rax # 24f188 <arr>
mov %rax,0x8(%rsp)
add $0xffffffffffffffff,%rbx
std::begin
also works for built-in arrays, which is very useful in template functions. – Kincardine++i
is probably more efficient thani++
because the latter returns an iterator by value – Absorptance