On clang version 5.0.1 the following code
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
string str = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 5000000; i++) {
str.substr(4);
}
return 0;
}
gives me the following timings
real 0m0.104s
user 0m0.096s
sys 0m0.002s
Now if I change it such that I have str.substr(3)
, I end up with the following timings
real 0m0.478s
user 0m0.468s
sys 0m0.003s
As far as I can tell gcc does not suffer from this. Could anyone shed any light on what may the problem here?
EDIT:
More importantly, might anyone have a suggestion about how to avoid this huge performance hit?
EDIT2:
It appears likely this is some kind of short string optimisation trickery, particularly since 22 is magic number in that context.