1

I'm wondering whether iterator will outperform brackets operator in a sequential access setting. Consider the following code snippets:

// v1.1
for (std::vector<int>::const_iterator it = v.begin(); it != v.end(); ++it) {
    do_something(*it);
}

// v1.2
for (size_t i = 0; i != v.size(); ++i) {
    do_something(v[i]);
}

// v1.3
std::vector<int>::const_iterator endIt = v.end();
for (std::vector<int>::const_iterator it = v.begin(); it != endIt; ++it) 
    do_something(*it);
}

// v1.4
size_t size = v.size();
for (size_t i = 0; i != size; ++i) {
    do_something(v[i]);
}

// v2.1
for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
    *it = it - v.begin(); // iterator arithmetic; expensive or not?
}

// v2.2
for (size_t i = 0; i != v.size(); ++i) {
    v[i] = i;
}

Has anyone ever done a benchmark for these? (Well, it depends on the compiler; let's take g++ 4.7 or 4.8 for instance.) Thanks.

4ae1e1
  • 7,228
  • 8
  • 44
  • 77
  • 2
    You already wrote the test cases you care about, why not just wrap them in a timers? FYI 1.1-1.4 should be identical, and all optimal. 2.1 and 2.2 will be cheap as dirt. – David May 03 '13 at 02:27

0 Answers0