Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster C++ String length() or size()?

length() returns the number of characters in the string and size() returns a size_t which is also the same but used to make it consistent with other STL containers.

For computing length(), the string iterates through all the characters and counts the length. So, O(n) time.

Is size() also the same ?

Or can size of a variable be computed directly in O(1) time ?

So, my question is, are they the same in terms of speed (as in how they are calculated) or is size computed in O(1) time ?

like image 703
ronilp Avatar asked Jul 25 '15 16:07

ronilp


People also ask

What is the difference between size () and length () in C++?

Using string::size: The method string::size returns the length of the string, in terms of bytes. Using string::length: The method string::length returns the length of the string, in terms of bytes. Both string::size and string::length are synonyms and return the exact same value.

What is the difference between strlen () and sizeof ()?

sizeof() vs strlen() vs size() Data Types Supported: sizeof() gives the actual size of any type of data (allocated) in bytes (including the null values), strlen() is used to get the length of an array of chars/string whereas size() returns the number of the characters in the string.

Is size and length the same in C++?

They are the same function; they even share documentation: en.cppreference.com/w/cpp/string/basic_string/size. They're both defined to be equivalent to distance(s. begin(), s. end()), where begin() and end() are iterators over CharT elements.

What is the size of string in C?

The string length in C is equal to the count of all the characters in it (except the null character "\0"). For Example, the string "gfddf" has a length of 5 and the string "4343" has a length of 4.


2 Answers

Both have the same complexity: Constant.

From the N4431 working draft, §21.4.4

size_type size() const noexcept;

Returns: A count of the number of char-like objects currently in the string. Complexity: Constant time.

And

size_type length() const noexcept;

Returns: size().


[...] iterates through all the characters and counts the length [...]

That's C strings you're thinking of.

like image 140
Daniel Jour Avatar answered Sep 23 '22 11:09

Daniel Jour


If you take a look at documentation here it says that length and size are the same.

Both string::size and string::length are synonyms and return the same value.

Also if you take a look at the code, length is cached, so the complexity is O(1). (Code from MS implementation but I'm sure other libraries are done the same way.)

size_type length() const _NOEXCEPT
    {   // return length of sequence
    return (this->_Mysize);
    }

size_type size() const _NOEXCEPT
    {   // return length of sequence
    return (this->_Mysize);
    }
like image 39
Jaka Konda Avatar answered Sep 21 '22 11:09

Jaka Konda