2

我很想知道为什么以下解决方案之一比另一个慢得多。让我们考虑以下代码:

// 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');
}}

为什么第二个这么慢?

4

1 回答 1

0

It is having to dereference a pointer every time you are comparing your iterator to 'a', instead of just comparing the actual char value. This is a negligible difference in most cases, but with it doing 1,000,000,000 iterations it is noticeable.

于 2013-04-29T15:47:17.470 回答