C++ std::string::empty
There are a few common ways check if a C++ std::string is empty (i.e. containing no characters):
-
s.empty() s == ""s == std::string()s.length() == 0ands.size() == 0
Let's compare some implementations of std::string.
Assembly showdown
| Library | Compiler | s.empty()
|
s.size() == 0
|
s == std::string()
|
s == ""
|
|---|---|---|---|---|---|
| libstdc++ | GCC 9.3 x86_64 -O2 |
|
|
||
| Clang 10.0.0 x86_64 -O2 |
|
|
|||
| Library | Compiler | s.empty()
|
s.size() == 0
|
s == std::string()
|
s == ""
|
| libc++ | Clang 10.0.0 x86_64 -O2 |
|
|
||
| Clang 10.0.0 x86_64 -O2 -fno-exceptions |
|
||||
| Library | Compiler | s.empty()
|
s.size() == 0
|
s == std::string()
|
s == ""
|
| STL | MSVC v19.24 x64 /O2t |
|
|
|
|
| MSVC v19.24 x64 /O2t /GS- |
|
||||
| Library | Compiler | s.empty()
|
s.size() == 0
|
s == std::string()
|
s == ""
|
Observations and analysis
- For each tested compiler and for each tested library, the code for
s.empty()ands.size() == 0is identical. - MSVC's code for
s == ""algorithmically the same as its code fors.empty(), but the implementation uses branches instead of using theseteinstruction. - MSVC's implementation and compiler out-performs all other tested
compilers in terms of the size of the generated code for
s == "",s.empty(), ands == "".
std::string library |
s.empty()
|
s.size() == 0
|
s == std::string()
|
s == ""
|
|---|---|---|---|---|
| libstdc++ | load size and test | call std::string::compare (not inlined) |
||
| libc++ | load and test SSO discriminator; branch and test size | load and test SSO
discriminator; branch and test size;
std::string::compare (not inlined) |
||
| STL | load size and test | load size and test; dead stores to stack; branch | load size and test; branch | |