------- Comment #17 from zackw at panix dot com 2006-07-13 04:23 ------- Subject: Re: poor optimization choices when iterating over a std::string (probably not c++-specific)
> One more comment, a loop with an early exit is whole issue and that is the > reason why all of the code in the loop is considered the header. There are a > couple of loop headers in this case, one for each exit which makes it harder > to > deal with in general. I didn't know that, and it is not obvious from the optimizer dumps. Thanks for explaining. > What you did not mention is which how would this loop exit normally, via the > return 1 or all the way through the loop. There is no enough information from > GCC's point of view to figure that out without profiling (for this case). GCC > is assuming that the loop exits in the first if statement which seems > reasoniable. Maybe you should try with profiling information and see what GCC > does for this testcase. <flamebait> Feedback-directed optimization is only good for making compilers look better on benchmarks. It's useless in real life. </> I can, in fact, get good code out of gcc 4.1 by beating it over the head with __builtin_expect, but I don't think I should have to do that. I think my suggested version is better code no matter whether or not the loop exits early. 4.2 still makes what I consider to be bad addressing mode choices after that change, but Zdenek did say he would look at that. It also puts the "return 1" exit block in the middle of the loop in spite of being told that all three conditions leading to that are unlikely. struct rep { unsigned long len; unsigned long alloc; unsigned long dummy; }; struct data { char * ptr; }; struct string { struct rep R; struct data D; }; int has_bad_chars(struct data *path) { char *c; for (c = path->ptr; __builtin_expect(c < path->ptr + ((struct rep *)path)[-1].len, 1); c++) { unsigned char x = (unsigned char)(*c); if (__builtin_expect(x <= 0x1f || x == 0x5c || x == 0x7f, 0)) return 1; } return 0; } -- http://gcc.gnu.org/bugzilla/show_bug.cgi?id=28364