开挂版本的strlen(出自VC运行库)

      随便翻翻网页,无意中发现一牛人博客中有个开挂版本的strlen。该strlen出现在VC运行库的源码中,其思想跟DSP汇编优化有点像。可惜学过DSP汇编却从没有想到把优化技术灵活运用,罪过罪过……

size_t strlen( const char* str )  
{  
    const char* ptr = str;  
    for ( ; ( ( int )ptr & 0x03 ) != 0; ++ptr )  
    {  
        if ( *ptr == '\0' )  
            return ptr - str;  
    }  
  
    unsigned int* ptr_d = ( unsigned int* )ptr;  
    unsigned int magic = 0x7efefeff;  
  
    while ( true )  
    {  
        unsigned int bits32 = *ptr_d++;  
        if ( ( ( ( bits32 + magic ) ^ ( bits32 ^ -1 ) ) & ~magic ) != 0 ) // bits32 ^ -1 等价于 ~bits32  
        {  
            ptr = ( const char* )( ptr_d - 1 );  
            if ( ptr[ 0 ] == 0 )  
                return ptr - str;  
            if ( ptr[ 1 ] == 0 )  
                return ptr - str + 1;  
            if ( ptr[ 2 ] == 0 )  
                return ptr - str + 2;  
            if ( ptr[ 3 ] == 0 )  
                return ptr - str + 3;  
        }  
    }  
}   
          据测该版本strlen比天真无邪版速度快3倍多。
原文地址:https://www.cnblogs.com/codingmylife/p/2532686.html