Gcc 7.1 -O3 这些都是相同的,godbolt.org/z/a-hc1d – jterm 4 月 25 日 3:27
原答案:
做了一些挖掘。下面是一个示例程序和相关程序集:
Code:
#include <string>
std::string get_string1(){ return ""; }
std::string get_string2(){ return std::string(); }
std::string get_string3(){ return {}; } //thanks Kerrek SB
int main()
{
get_string1();
get_string2();
get_string3();
}
集会:
__Z11get_string1v:
LFB737:
.cfi_startproc
pushl %ebx
.cfi_def_cfa_offset 8
.cfi_offset 3, -8
subl $40, %esp
.cfi_def_cfa_offset 48
movl 48(%esp), %ebx
leal 31(%esp), %eax
movl %eax, 8(%esp)
movl $LC0, 4(%esp)
movl %ebx, (%esp)
call __ZNSsC1EPKcRKSaIcE
addl $40, %esp
.cfi_def_cfa_offset 8
movl %ebx, %eax
popl %ebx
.cfi_restore 3
.cfi_def_cfa_offset 4
ret $4
.cfi_endproc
__Z11get_string2v:
LFB738:
.cfi_startproc
movl 4(%esp), %eax
movl $__ZNSs4_Rep20_S_empty_rep_storageE+12, (%eax)
ret $4
.cfi_endproc
__Z11get_string3v:
LFB739:
.cfi_startproc
movl 4(%esp), %eax
movl $__ZNSs4_Rep20_S_empty_rep_storageE+12, (%eax)
ret $4
.cfi_endproc
这是用编译的-std=c++11 -O2
.
可以看到,还有很多工作要做return "";
声明和相对较少的return std::string
and return {};
(这两个是相同的)。
正如弗里希·拉贝(Frerich Raabe)所说,当经过一个空的C_string
,它仍然需要对其进行处理,而不仅仅是分配内存。看来这不能被优化掉(至少不能被 GCC 优化)
所以答案肯定是使用:
return std::string();
or
return {}; //(c++11)
虽然除非你回来a lot性能关键代码中的空字符串(我猜是日志记录?),差异仍然是微不足道的。