C ++ for range loop is faster than decrementing loop

We often iterate over arrays starting with the last elument like this:

static const char* pszStrings[] = { ... }
for (size_t i = _countof(pszStrings); i--;)
    use(pszStrings[i]);

      

My question is that the new for loop based loop is efficient and therefore used:

static const char* pszStrings[] = { ... }
for (auto string : pszStrings)
    use(string);

      

Additionally...

Since I canโ€™t look at the generated code, and even if, I donโ€™t know, if I could draw the correct conclusions, I would be happy with not too scientific answers.

+3


source to share


1 answer


The compiler can make many assumptions about the iterated collection in the new one range for-loop

, which is in the previously written for-loop. Example:

In C ++ 98 days one usually writes:

for (std::vector<int>::const_iterator it = v.begin(), it_end = v.end(); 
     it != it_end; ++it) {
    // code ..
}

      

Used it_end

because in many cases the compiler could not be sure that the collection would not resize inside the for loop (and .end()

might change). If you write:

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

      

The compiler can generate a function call .end()

for each loop execution.



range for-loop

efficient (several times more efficient) than the old one for the loop.

Some examples:

If you have a loop iterating std::vector

over index:, for (int i = 0; i < v.size(); ++i)

that loop will need to index the vector to use element ( v[i]

), which most likely won't be a noticeable expectation, but when the vector is really big, you can see it in a narrow loop.

This type of loop will improve when upgraded to range for-loop

.

The first loop in the answer would most likely not improve in performance, but in clarity, the reader of the code would know that the code is meant to iterate through the entire collection and not skip some (in the old way, you might recognize for-each pattern

in a for loop, but that is tedious and can lead to erroneous conclusions (perhaps the index or iterator is changed in the body) about the code if not careful.

+5


source







All Articles