Typical strlen()
traverse from first character till it finds \\0
.
This requires you to traverse each and every character.
In algorithm sense, its O(N).
Obviously, if your string has a known minimum length, you can begin your search at that position.
Beyond that, there's not really anything you can do; if you try to do something clever and find a \0
byte, you still need to check every byte between the start of the string and that point to make sure there was no earlier \0
.
That's not to say that strlen
can't be optimized. It can be pipelined, and it can be made to process word-size or vector chunks with each comparison. On most architectures, some combination of these and other approaches will yield a substantial constant-factor speedup over a naive byte-comparison loop. Of course, on most mature platforms, the system strlen
is already implemented using these techniques.