Sign in to follow this  

[C++] !std::string.empty() vs. std::string.size()

This topic is 4228 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If I want to know if a std::string object is empty or not would it be more efficient to use:
if(!string.empty())
{
	...
}

or

if(string.size())
{
	...
}
It's probably a trivial difference, but I want to pick one to maintain a consistent coding style.

Share this post


Link to post
Share on other sites
Well, the former is more expressive, don't you think? Also, the standard allows the latter to be slower (it *may* be O(n)), but I don't think there exists an implementation where it actually is.

Share this post


Link to post
Share on other sites
There is probably no std::string implementation "which counts" which has O(n) length(), but there are definitely std::list implementations which do. (Only one of .length() and .splice() for a std::list can be O(1) and the other has to be O(n): if you track the length, then you have to count up the nodes that are being spliced in when you splice them).

But checking with .empty() *can't* be *slower*, and is more specific about what you mean; so you should do it that way.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
As a general rule: always use the most specialized method of an interface

and that's clearly >empty<

Share this post


Link to post
Share on other sites

This topic is 4228 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this