How to write a better strlen function?

后端 未结 7 1956
Happy的楠姐
Happy的楠姐 2020-12-30 06:43

I am reading \"Write Great Code Volume 2\" and it shows the following strlen impelementation:

int myStrlen( char *s )
{
    char *start;
    start = s;
    w         


        
7条回答
  •  情书的邮戳
    2020-12-30 07:35

    For starters, this is worthless for encodings like UTF-8... that is, calculating the number of characters in an UTF-8 string is more complicated, whereas the number of bytes is, of course, just as easy to calculate as in, say, an ASCII string.

    In general, you can optimize on some platforms by reading into larger registers. Since the other links posted so far don't have an example of that, here's a bit of pseudo-pseudocode for lower endian:

    int size = 0;
    int x;
    int *caststring = (int *) yourstring;
    while (int x = *caststring++) {
      if (!(x & 0xff)) /* first byte in this int-sized package is 0 */ return size;
      else if (!(x & 0xff00)) /* second byte etc. */ return size+1;
      /* rinse and repeat depending on target architecture, i.e. twice more for 32 bit */
      size += sizeof (int);
    }
    

提交回复
热议问题