在c ++中获取const char*长度的最佳方法

Jam*_*Alb 6 c++ string-length strlen

我知道获得const char长度的两种方法*

const char * str = "Hello World !";
int Size = 0;
while (str[Size] != '\0') Size++;
Run Code Online (Sandbox Code Playgroud)

和其他方式很简单

const char * str = "Hello World !";
size_t Size = strlen(str);
Run Code Online (Sandbox Code Playgroud)

但我不想使用str lib函数strlen,我认为这个函数也使用我的第一种方式行为.因为在PC世界中,当我们想要计算一些东西时,我们需要计算每个块的数量,并且没有魔法来获得一个运动的长度所以我认为第一种方式是获得长度的最佳选择const char *.换句话说,我认为第一种方式对于重型弦乐来说可能太重了.所以我很困惑.哪种方式更好,为什么其他方式不是?

小智 16

让我们检查这两种方法的汇编列表.

#include <cstddef>
#include <cstring>

int string_size_1()
{
    const char * str = "Hello World !";
    int Size = 0;
    while (str[Size] != '\0') Size++;
    return Size;
}

int string_size_2()
{
    const char * str = "Hello World !";
    size_t Size = strlen(str);
    return Size;
}
Run Code Online (Sandbox Code Playgroud)

使用带有标志的Clang 4.0.0 -std=c++14 -O2

string_size_1():                     # @string_size_1()
        mov     eax, 13
        ret

string_size_2():                     # @string_size_2()
        mov     eax, 13
        ret
Run Code Online (Sandbox Code Playgroud)

链接:https://godbolt.org/g/5S6VSZ

两种方法最终都具有完全相同的装配清单.此外,编译器优化掉所有内容并返回一个常量,因为字符串文字在编译时是已知的.所以,就性能而言,它们同样好.

但就可读性而言,strlen(str)肯定更好.函数调用通过函数名称表明意图.循环不能这样做.


此外,std::stringstd::string_view比在许多情况下,C-串更好.考虑一下.