faster strlen?

后端 未结 8 2158
小鲜肉
小鲜肉 2021-02-20 15:49

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).

8条回答
  •  清歌不尽
    2021-02-20 16:09

    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.

提交回复
热议问题