KoblentsBlog Photography
Contact About
Ches
Iterators, Access, and Insert
I had assumed simpler code for access -> faster access; this is one of the many things I learned in java that I am relearning/refreshing for C++.
Summary: using iterators is faster than any other method of access (that I know of). Reference

123
for (std::vector<T>::iterator it = vec.begin(); it != vec.end(); it++) {
     use <i>it</i> or <i>*it</i> somehow;
}

Is significantly faster than
1
for (uint32 i = 0; i < vec.size(); i++) { use <i>vec[i]</i> somehow; }

And much much faster than access via vec.at(i), as that checks for bounds.
 
Similarly, my benchmarks (with -OX g++ optimization flags making no difference to the outcome, though they did speed things up) showed faster map copying with
destination.insert(source.begin(), source.end())

faster than
12345
std::copy(
     source.begin(),
     source.end(),
     std::iterator(destination, destination.begin())
);

Which makes sense since inserting an ordered list in this manner is much quicker, since inserts have to figure out the position at which to insert. For copying to a blank map, this is a no-brainer (sequential copy); for copying to a populated map, it still improves speed as the logarithmic search has fewer positions to search over.
Ches Koblents
September 6, 2012
 
« Newer Older »
© Copyright Koblents.com, 2012-2024