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

Started by
3 comments, last by GameDev.net 17 years, 11 months ago
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.
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.
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.
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.
As a general rule: always use the most specialized method of an interface

and that's clearly >empty<

This topic is closed to new replies.

Advertisement