Re: Iterators are much slower than pointers

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance




grober@xxxxxxxx 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?

.



Relevant Pages

  • Re: what is wrong with this code?
    ... read with fgetc or fgets as string, and convert every two characters to integer. ... You can use loop to convert 2 chars each, but you need to know when to exit ...
    (microsoft.public.vc.language)
  • Re: fgets not doing as I expect.
    ...  Any pointers? ... int main{ ... Each pass through the loop ... it reads up to 7 chars from stdin and prints them. ...
    (comp.lang.c)
  • Re: Fridays the thirteenth. (And a little puzzle.)
    ... -- compiler) is the usual method ... int febdays ... -- We're going to go round a loop dealing with each year in turn. ... -- other languages call) ...
    (uk.people.silversurfers)
  • Re: C code is not generating required results.
    ... int main ... the array by the size of an element. ... prevent the user of your program from entering more characters than ... want to loop. ...
    (comp.lang.c)
  • Re: long double versions of functions in gcc under Cygwin
    ... rather than the nearest enclosing one) and a decent exception ... them it doesn't seem like goto usage would be affected ... int typfun() ... Why use a for loop when it is just a while loop in disguise? ...
    (comp.lang.c)