Question: Why is return "";
faster than return {};
when initializing an empty std::string
?
To answer this question, we can look at the generated assembly code when compiling the two functions, make_default()
and make_empty()
:
#include <string>
std::string make_default() {
return {};
}
std::string make_empty() {
return "";
}
Compiling the two functions with Clang 16 and libc++ produces the following assembly code:
make_default():
mov rax, rdi
xorps xmm0, xmm0
movups xmmword ptr [rdi], xmm0
mov qword ptr [rdi + 16], 0
ret
make_empty():
mov rax, rdi
mov word ptr [rdi], 0
ret
See live example at Compiler Explorer.
The assembly code for make_default()
zeroes out 24 bytes in the std::string
container, while make_empty()
only zeroes out 2 bytes. This is why return "";
is faster than return {};
when creating an empty std::string
.