Question

I'm currently writing an application which needs to perform as good as it can be. I'm using VS2012 as my IDE (and compiler).

I've noticed, as I'm iterating over vectors, that a pointer solution in contrast to iterator, is much quicker in terms of speed. Why is that? I mean, an iterator is basicly the same thing. It should be at least.

Take a look at this example:

std::vector<int> v;
for (std::vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    // Do stuff with *it
}

for (int* i = &v[0], i <= &v[v.size()-1]; i++) {
    // Do stuff with *i
}

Is there any optimization that is needed by the compiler? I'm using all the standard settings, so -O2 is already enabled. Thanks in advance.

EDIT: I'm compiling in Release, and running with Ctrl+F5 (without debugging that is).

EDIT2: The actual source-code is an implementation of quicksort. Here is a link to the full source, its very short so check it out.

Was it helpful?

Solution

I'm currently writing an application which needs to perform as good as it can be.

Then grab a profiler and look where the real bottlenecks are. In optimized code (Release mode), of course.

-O2 is not everything in VS2012: there are several #defines that manipulate the behavior of standard container iterators wrt to bounds checking and other security checks. You might want to look them up ("checked iterators" and "secure SCL" might lead you to the right sites) and set them accordingly.

But I very much doubt that the iteration over containers will be your bottleneck, there will be other sections of code that are more sensitive to performance issues.

OTHER TIPS

One potential reason is that you are post-incrementing your iterator rather than pre-incrementing it. Try this instead:

for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)

This may not increase your speed since some (maybe most) compilers optimize away this issue. However, sometimes when you post-increment, a temporary copy of the old iterator value must be made to allow it to return what you'd expect in the loop. It's something to try anyway.

One easy way to increase performance is not to do the end method on each iteration - also do ++it not it++.

i.e.

std::vector<int> v;
const std::vector<int>::iterator end = v.cend();
for (std::vector<int>::iterator it = v.begin(); it != end; ++it) {
    // Do stuff with *it
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top