Why reimplement strlen as loop+subtraction?

后端 未结 2 2048
粉色の甜心
粉色の甜心 2021-02-18 18:59

Inspired by this question about the following code from SQLite3:

 static int strlen30(const char *z){
    const char *z2 = z;
    while( *z2 ){ z2++; }
    retur         


        
2条回答
  •  情歌与酒
    2021-02-18 19:32

    Why reimplement strlen as loop+subtraction?

    I suspect the real answer is that the programmer felt like it, but another potential justification/rationalisation is that the loop is inline (independent of whether strlen30 itself is), whereas on many systems strlen is an out-of-line function call (e.g. Linux/GCC). If the overwhelming majority of strings are empty or short (despite the "special" treatment of long ones), then that may yield a slight performance bump for the common case. That possibility alone may be enough to get a code-happy programmer key-tapping. For longer strings I would expect the library strlen to be generally optimal (allowing for it's lack of knowledge of the application specific length of strings).

    Some systems may not even benefit from this inlining as strlen provides it's own, or an inline/out-of-line hybrid with a quick inline check for empty, one-char, maybe two-char strings then a call.

提交回复
热议问题