Domanda

Does dereferencing a string iterator have a big impact on performance?

I have a loop that runs many times (C++)

for (string::const_iterator it = myString.begin; it != myString.end(); it++) {
    do lots of things on *it;
}

and since i don't know (and couldn't find) how the * operator is implemented for string::const_iterator i want to know if using a char a = *it would be better than just *it

È stato utile?

Soluzione

Unless you're using a debugging version of the library, a string iterator should be no more than a pointer, and dereferencing it should do no more than dereference the pointer.

The pointer is likely to be wrapped in a class type (although that's not required; the pointer itself would make a valid iterator); but that won't add any overhead.

As with a pointer, you might benefit from holding a local copy of its target, since that can be placed in a register; but the compiler might well make that optimisation anyway, if it can see that the value in memory won't change. The only way to be sure which is better is try both variants, and measure it and/or study the generated assembly.

Altri suggerimenti

For string, the iterator (generally) just resolves to a pointer (same as the vector iterator) in release mode. Any compiler worth its salt will cache the deference, so performance hits should theoretically be non-existant. But the rule of thumb is: when in doubt, measure.

The is allin release mode.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top