3 ms·
A fun one in C is: for(int i = 0; i < strlen(s); i++) doSomething(s[i]); strlen() searches for the terminating NUL byte and is thus O(n), which ma
by mikeash 12y ago
A fun one in C is:
for(int i = 0; i < strlen(s); i++)
doSomething(s[i]);
strlen() searches for the terminating NUL byte and is thus O(n), which makes the loop quadratic.
What makes this especially fun is that strlen is part of the standard library and has defined semantics. That means the compiler is free to hoist the strlen call out of the loop if it can prove that it wouldn't alter the standards-specified behavior, like if you never modify the contents of the string. That means your asymptotic performance will depend on which compiler you're using and even which optimization level you're using.
- nightcracker 12y agoThe effect you're describing can happen to any inlined function.
- QuercusMax 12y agoOf course a better way of doing it in C is: for (char* p = s; *p; p++) { doSomething(*p); }