Archived

This topic is now archived and is closed to further replies.

Toolmaker

Vector and iterators: Single, or double dereference?

Recommended Posts

Toolmaker    967
I was have a conversation with someone about what would be more efficient, using an index or iterators or move along my vector. I would say iterators, because it is only 1 derefence inside my loop: strcmp(it->szName, Field.szName) However, he said it could be 2 dereferenes, and even a function call if it was overloaded. But, I am using a struct, so the -> operator isn''t overloaded. And, moveing around some pointers doesn''t require them to be dereferenced. Any input? Toolmaker
-Earth is 98% full. Please delete anybody you can.

Share this post


Link to post
Share on other sites
Sneftel    1788
iteration through a vector using an index variable is likely to be more or less identical to using an iterator. In each case, moving to the next element requires an add, and accessing the current element requires an indirect memory read.

Most STL functions are inlined by most compilers, so there isn''t likely to be a function call overhead. Furthermore, keep in mind that an index dereference (square brackets) is even more likely to incur a function call than an iterator dereference, since vector iterators are often implemented as pointers.


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
Shannon Barber    1681
Iterators are heavily abstracted from pointers. On a good optimizing compiler it should be the same when optimizations are enabled (when they are not enabled, it will be much slower).

Once fully optimized, vector iterators are raw pointers, and incrementing a pointer and comparing to the terminating case is the optimal solution. Indexed derefencing (i.e. stuff[j]) used to take a bit longer on older machines (<586), and it may still be slightly slower (you''d have to get the instruction set refence and count clock ticks to check).

In a release build you probably won''t be able to tell the difference.


Now, if you''re not using an optimizing compiler, not using a good one, or not using optimizations, there can be a significant difference.

Share this post


Link to post
Share on other sites