Jump to content
  • Advertisement
Sign in to follow this  
Gondolin

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

This topic is 4444 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
Advertisement
empty() may be more efficient. Probably not for a string, but it is easy to see how it could be so for a linked list.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!