天天看點

高效的strlen函數

一般來說,一個入門的程式員大概可以不費勁的寫出這樣的 strlen 代碼。

size_t my_strlen(const char * str) {
<span style="white-space:pre">	</span>size_t length = 0 ;
<span style="white-space:pre">	</span>while (*str++ )
<span style="white-space:pre">	</span>++ length;
<span style="white-space:pre">	</span>return  length;
}
           

那我們再來看看,glibc函數庫裡面的strlen是如何實作的。

#include <string.h>
#include <stdlib.h>
           
<pre name="code" class="cpp">size_t strlen(const char *str) {
    const char *char_ptr;
    const unsigned long int *longword_ptr;
    unsigned long int longword, himagic, lomagic;

    /* Handle the first few characters by reading one character at a time.
       Do this until CHAR_PTR is aligned on a longword boundary.  */
    for (char_ptr = str; ((unsigned long int) char_ptr
            & (sizeof (longword) - 1)) != 0;
            ++char_ptr)
        if (*char_ptr == '\0')
            return char_ptr - str;

    /* All these elucidatory comments refer to 4-byte longwords,
       but the theory applies equally well to 8-byte longwords.  */

    longword_ptr = (unsigned long int *) char_ptr;

    /* Bits 31, 24, 16, and 8 of this number are zero.  Call these bits
       the "holes."  Note that there is a hole just to the left of
       each byte, with an extra at the end:

       bits:  01111110 11111110 11111110 11111111
       bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD

       The 1-bits make sure that carries propagate to the next 0-bit.
       The 0-bits provide holes for carries to fall into.  */
    himagic = 0x80808080L;
    lomagic = 0x01010101L;
    if (sizeof (longword) > 4) {
        /* 64-bit version of the magic.  */
        /* Do the shift in two steps to avoid a warning if long has 32 bits.  */
        himagic = ((himagic << 16) << 16) | himagic;
        lomagic = ((lomagic << 16) << 16) | lomagic;
    }
    if (sizeof (longword) > 8)
        abort();

    /* Instead of the traditional loop which tests each character,
       we will test a longword at a time.  The tricky part is testing
       if *any of the four* bytes in the longword in question are zero.  */
    for (;;) {
        longword = *longword_ptr++;

        if (((longword - lomagic) & ~longword & himagic) != 0) {
            /* Which of the bytes was the zero?  If none of them were, it was
               a misfire; continue the search.  */

            const char *cp = (const char *) (longword_ptr - 1);

            if (cp[0] == 0)
                return cp - str;
            if (cp[1] == 0)
                return cp - str + 1;
            if (cp[2] == 0)
                return cp - str + 2;
            if (cp[3] == 0)
                return cp - str + 3;
            if (sizeof (longword) > 4) {
                if (cp[4] == 0)
                    return cp - str + 4;
                if (cp[5] == 0)
                    return cp - str + 5;
                if (cp[6] == 0)
                    return cp - str + 6;
                if (cp[7] == 0)
                    return cp - str + 7;
            }
        }
    }
}
           

很明顯這段代碼比我們自己寫的版本要複雜多了。其中注釋寫的比較清楚,我也不翻譯了。

下面主要對其中幾個點做分析吧。如果要看更詳細的,請點選《strlen源碼剖析》

簡單版本和glibc版本主要的差別在于:通過記憶體對齊,來加快CPU的讀取速度。

(在計算機在讀取記憶體中的資料的時候,在記憶體對齊的狀态下一次讀取一個word的資料,是最節省時間的。例如在32位的計算機中,一個WORD為4 byte,則WORD資料的起始位址能被4整除的時候CPU的存取效率比較高。)

其中用到了兩個技巧:

(1)由于傳進來的字元串的位址有可能不是4位元組(long int)對其的,是以首先找到4位元組對其的那個位址

(2)技巧就是如何高效的判斷在讀取的4個位元組中是否有位元組為0

是以這個算法的整體思路如下:

(1)從字元串的開頭開始,一次判斷一個字元直到記憶體對齊(也就是位址能被4整除)。

(2)如果在記憶體對齊之前,字元串就已經結束了(也就是讀取到'\0'),那麼就return,否則到繼續下一步;

(3)一次讀入并判斷一個DWORD,如果此DWORD中沒有為0的位元組,則繼續下一個DWORD;如果判斷出有'\0',就跳到下一步。

(4)找出該DWORD中第一個為0的位元組的位置,然後return。

  • IT從業人員需要及時關注技術動态,但是網際網路的内容卻過于離散,好東西往往隐藏得很深。 現在可以在微信公衆号裡面 搜尋關注 “小魚兒的IT技術分享” ,訂閱我為大家每天彙總的IT技術資訊。歡迎大家關注!
    • 有興趣的請點選《與IT技術相關的微信公衆号》

繼續閱讀