Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have read that use of strlen is more expensive than such testing like this:

We have a string x 100 characters long.

I think that

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

is more expensive than this code:

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

Is it true? Maybe the second code will not work in some situation so is it better to use the first?

Will it be better with the below?

for (char *tempptr = x; *tempptr != '\0'; tempptr++) 
like image 360
dato datuashvili Avatar asked Aug 02 '10 13:08

dato datuashvili


People also ask

Does strlen consider null character?

The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.

What is the time complexity of strlen?

The time complexity of standard strlen is O(n). Since all trailing characters are '\0', we can use binary search. By comparing middle two elements with '\0', we can decide whether we need to recur for left half or right half. IF one of them is \0, then we found the first occurrence.

What is the use of strlen () function?

The strlen() function determines the length of string excluding the ending null character. The strlen() function returns the length of string . This example determines the length of the string that is passed to main() .

Does strlen include null byte?

strlen() counts the number of characters up to, but not including, the first char with a value of 0 - the nul terminator.


2 Answers

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

This code is calling strlen(x) every iteration. So if x is length 100, strlen(x) will be called 100 times. This is very expensive. Also, strlen(x) is also iterating over x every time in the same way that your for loop does. This makes it O(n^2) complexity.

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

This code calls no functions, so will be much quicker than the previous example. Since it iterates through the loop only once, it is O(n) complexity.

like image 94
MatthewD Avatar answered Oct 09 '22 17:10

MatthewD


The first code checks length of x in every iteration of i and it takes O(n) to find the last 0, so it takes O(n^2), the second case is O(n)

like image 26
Artyom Avatar answered Oct 09 '22 16:10

Artyom