为什么要重新实现strlen的作为循环+减法? [英] Why reimplement strlen as loop+subtraction?

查看:166
本文介绍了为什么要重新实现strlen的作为循环+减法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启发这个问题了解从sqlite3的以下code:

 静态INT strlen30(为const char * Z){
    为const char * Z2 = Z;
    而(* Z2){Z2 ++; }
    返回0x3fffffff&安培; (INT)(Z2 - Z);
 }

这是伴随着提交信息< /一>,说这个函数与帮助 INT 溢出。

我在这个部分特别感兴趣:

 为const char * Z2 = Z;
 而(* Z2){Z2 ++; }

我这个循环的进步 Z2 直到 Z2 点到空终止符。然后 Z2-Z 产生的字符串长度。

为什么不使用的strlen()这部分并改写如下:

 返回0x3fffffff&安培; (中间体)(strlen的(Z));

为什么要使用循环+减法,而不是的strlen()?有什么可以循环+减法做什么的strlen()不能?


解决方案

  

为什么要重新实现的strlen作为循环+减法?


我怀疑真正的答案是,程序员喜欢它的感觉,但另一个潜在的理由/合理化的循环是内联(独立是否 strlen30 本身就是),而在许多系统上的strlen 是超出线的函数调用(如Linux的/ GCC)。如果绝大多数的字符串是空的或短(尽管特殊待遇的人长的),则可能会产生轻微的性能提升对于通常的情况。单凭这个可能性可能是足以让一个code-快乐编程键窃听。对于更长的字符串我希望库的strlen 要普遍最优(允许它缺乏字符串的应用特定长度的知识)。

有些系统甚至有可能不会从这个内联为的strlen 中获益提供了它自己的,或内联/外网上的混合动力车具有快速内嵌检查空一-char,也许两个字符的字符串,然后拨打电话。

Inspired by this question about the following code from SQLite3:

 static int strlen30(const char *z){
    const char *z2 = z;
    while( *z2 ){ z2++; }
    return 0x3fffffff & (int)(z2 - z);
 }

that is accompanied by a commit message saying this function helps with int overflows.

I'm particularly interested in this part:

 const char *z2 = z;
 while( *z2 ){ z2++; }

to me this loop advances z2 until z2 points onto null terminator. Then z2-z yields the string length.

Why not use strlen() for this part and rewrite like this:

return 0x3fffffff & (int)(strlen(z));

Why use loop+subtraction instead of strlen()? What can loop+subtraction do what strlen() can't?

解决方案

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.

这篇关于为什么要重新实现strlen的作为循环+减法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆