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

ronilp picture ronilp · Jul 25, 2015 · Viewed 17.3k times · Source

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 ?

Answer

Daniel Jour picture Daniel Jour · Jul 25, 2015

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.