Re: Iterators are much slower than pointers
grober@arcor.de wrote:
The following code copies the contents of a string into a vector of
chars a million times.
Not really, why don't you print the vector's address over each loop?
The problem is that the version that uses begin() and end() iterators
is much slower than the version that uses the begin and end pointers
under Visual C++ 2005. (see comments)
Of course, an iterator is generated in order to verify *if* any element
needs to be overwitten.
Is there a way to make both versions equal fast? I tried to define
_SECURE_SCL to 0 before including the headers, but it doesn't make it
faster.
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::string s(2000, '\0');
for(int i = 0; i < 1000000; ++i)
{
// comment out one of the two lines before testing the
code
//std::vector<char> v(s.begin(), s.end()); // slow version, takes ~14
seconds
//std::vector<char> v(s.data(), s.data() + s.length()); // fast
version, takes ~1 second
}
}
Try something like the following so you can observe the output:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
std::ostream& operator<<(std::ostream& os, std::vector<char>& vc)
{
os << "adress of vector = " << &vc << "\t";
std::copy(vc.begin(), vc.end(), std::ostream_iterator<char>(os));
return os;
}
int main()
{
for(int i = 0; i < 1000000; ++i)
{
std::string s(10, (i%2)?'a':'b'); // alternate
// std::vector<char> v(s.begin(), s.end());
std::vector<char> v(s.data(), s.data() + s.size());
std::cout << v << std::endl;
}
return 0;
}
What are your results now?