Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the length of a string in C efficiently?

How to calculate the length of a string in C efficiently (in time)?

Right now I'm doing:

int calculate_length(char *string) {
    int length = 0;
    while (string[length] != '\0') {
        length++;
    }
    return length;
}

But it's very slow compared to strlen() for example, is there any other way to do it?

Thanks.

EDIT: I'm working in a freestanding environment, I'm not allowed to use any external lib including "string.h".

like image 622
Carla Álvarez Avatar asked Sep 07 '25 16:09

Carla Álvarez


2 Answers

From the FreeBSD source code:

size_t
strlen(const char *str)
{
    const char *s;
    for (s = str; *s; ++s);
    return(s - str);
}

Compared to your code, this probably maps very nicely to an assembler instruction, which can explain a big performance difference.

like image 84
Andomar Avatar answered Sep 09 '25 21:09

Andomar


strlen(). Odds are, if somebody had found a better, faster generic method, strlen would have been replaced with that.

like image 25
aib Avatar answered Sep 09 '25 20:09

aib