Alex Rivera | Logout

Is using strlen() in the loop condition slower than just checking for the null character?

Asked 2010-08-02T13:07:18.100
28

I have read that using strlen is more expensive than testing for the null character:

We have a string x which is 100 characters long.

I think that

for (int i = 0; i < strlen(x); i++)

is more expensive than this

for (int i = 0; x[i] != '\0'; i++)

Is it true? Does the second code work in every situation or are there exceptions?

Would using pointers like below be better?

for (char *tempptr = x; *tempptr != '\0'; tempptr++)
Edit
Report

1 Answer

5

Yes your second may not work 100% percent of the time but it would be slighty quite. This is because when using strlen() you have to call the method each time. A better way would be like so

int strLength = strlen(x);
for (int i = 0; i < strLength; i++)

Hope this helps.

answered 2010-08-02T13:13:59.320

Your Answer