4 ms·
In most cases I expect the C compiler to hoist the strlen out of the loop (I don't know whether it will in practice, but the V8 compiler for Javascript will def
by richardwhiuk 12y ago
In most cases I expect the C compiler to hoist the strlen out of the loop (I don't know whether it will in practice, but the V8 compiler for Javascript will definitely make a similar harder optimization, so it doesn't seem unlikely).
- umanwizard 12y agoI just tested this with GCC (gcc -S test.c --std=c99) and it doesn't optimize out the strlen inside the loop if the string is a variable (even if defined by const char *foo = "constant string";). If you're calling strlen on a constant string directly, it is indeed smart enough to optimize it out.
- eropple 12y agoThis is the correct behavior. It's not like they're immutable strings, or even that the variable's guaranteed to be pointed at the same place on every iteration of the loop. (You could say that a sufficiently smart static analyzer should be able to do that...but that static analyzer better ask about that thread you're running over there...) Compilers have a limit to how smart they can be, and that totally makes being smart about your stuff all the more important.
- umanwizard 12y agoAs far as I understand, a string defined as const char * can be treated as immutable. Casting away a const qualifier and then modifying the referenced value is undefined behavior.