我很想知道为什么以下解决方案之一比另一个慢得多。让我们考虑以下代码:
// create a very long string
int x,y;
bool b;
char c[10000];
for (x=0;x<10000;x++)
c[x]='a';
string s(c);
现在我想遍历字符串并将每个字符与其他字符进行比较。第一个解决方案在 5 秒内完成任务:
for (y=0;y<100000;y++){
for (x=0;x<10000;x++){
b = (s[x]=='a');
}}
第二个在 21 秒内:
string::iterator begin = s.begin();
string::iterator end = s.end();
string::iterator i;
for (y=0;y<100000;y++){
for (i=begin;i<end;i++){
b = (*i=='a');
}}
为什么第二个这么慢?
最佳答案
每次将迭代器与“a”进行比较时,都必须取消对指针的引用,而不仅仅是比较实际的 char 值。在大多数情况下,这是一个可以忽略不计的差异,但是当它进行 1,000,000,000 次迭代时,它是显而易见的。
关于c++ - 使用指针缓慢迭代字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16215699/