Best way to get length of const char * in c++

JamesAlb picture JamesAlb · Jun 22, 2017 · Viewed 37.1k times · Source

i know two way's to get length of const char *

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

and other way is very simple

const char * str = "Hello World !";
size_t Size = strlen(str);

but i don't want to use str lib functions like strlen and i think this function use my first way behavior too. because in the pc world when we want to count something we need to count each block's and there is no magic to get the length with one movement so i think the first way is the best option to get length of const char *. other way i think the first way is maybe too heavy for heavy string's. so im confused. which way is better and why other way is not ?

Answer

user2486888 picture user2486888 · Jun 22, 2017

Let's inspect the assembly listing of these two methods.

#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;
}

Using Clang 4.0.0 with flags -std=c++14 -O2

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

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

Link: https://godbolt.org/g/5S6VSZ

Both methods end up with exactly the same assembly listing. Also, the compiler optimizes away everything and just return a constant because the string literal is known during compile-time. So, in terms of performance, they are equally good.

But in terms of readability, strlen(str) is definitely better. A function call states the intention through the function name. A loop cannot do that.


Besides, std::string and std::string_view are more preferable than C-string in many cases. Consider them.