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".
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.
strlen()
. Odds are, if somebody had found a better, faster generic method, strlen would have been replaced with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With