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

Issue

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”.

Solution

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.

Answered By – Andomar

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *