Skip to main content
gamedev.net
🔒 Locked

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

Started by Mindowindow May 21, 2006 at 2:45 PM 3 replies 5.6k views
Original Post
Mindowindow
Mindowindow
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.
bakery2k1
bakery2k1
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.
Sharlin
Sharlin
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.
Zahlman
Zahlman
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.