Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

faster strlen?

Typical strlen() traverse from first character till it finds \0. This requires you to traverse each and every character. In algorithm sense, its O(N).

Is there any faster way to do this where input is vaguely defined. Like: length would be less than 50, or length would be around 200 characters.

I thought of lookup blocks and all but didn't get any optimization.

like image 375
Jack Avatar asked Nov 21 '09 07:11

Jack


People also ask

What can I use instead of strlen?

strlen() in C-style strings can be replaced by C++ std::strings. sizeof() in C is as an argument to functions like malloc(), memcpy() or memset() can be replaced by C++ (use new, std::copy(), and std::fill() or constructors).

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.

Is strlen unsafe?

Strlen is not safe to call! Unless you positively know that the string is null- terminated... Are all the functions you use guaranteed to return a null- terminated string?

What strlen means?

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


2 Answers

Sure. Keep track of the length while you're writing to the string.

like image 175
Bob Aman Avatar answered Sep 19 '22 20:09

Bob Aman


Actually, glibc's implementation of strlen is an interesting example of the vectorization approach. It is peculiar in that it doesn't use vector instructions, but finds a way to use only ordinary instructions on 32 or 64 bits words from the buffer.

like image 37
Pascal Cuoq Avatar answered Sep 20 '22 20:09

Pascal Cuoq