c++ - Slow iterating over string using pointers -
i love see why 1 of following solution slower other. lets concider following code:
// create long string int x,y; bool b; char c[10000]; (x=0;x<10000;x++) c[x]='a'; string s(c);
now want iterate on string , compare each character other. first solution completes task in 5 seconds:
for (y=0;y<100000;y++){ (x=0;x<10000;x++){ b = (s[x]=='a'); }}
and second in 21 seconds:
string::iterator begin = s.begin(); string::iterator end = s.end(); string::iterator i; (y=0;y<100000;y++){ (i=begin;i<end;i++){ b = (*i=='a'); }}
why second slower?
it having dereference pointer every time comparing iterator 'a', instead of comparing actual char value. negligible difference in cases, doing 1,000,000,000 iterations noticeable.