Ha scavato. Di seguito è riportato un programma di esempio e l'assemblea in questione:
Codice:
#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();
}
Assemblea:
__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
Questo è stato compilato con -std=c++11 -O2
.
Si può notare che c'è molto più lavoro per la dichiarazione return "";
e relativamente piccola per return std::string
e return {};
(questi due sono identici).
Come ha detto Frerich Raabe, quando si passa uno C_string
vuoto, è ancora necessario eseguire l'elaborazione su di esso, invece di allocare solo memoria. Sembra che questo non può essere ottimizzata di distanza (almeno non da GCC)
Quindi la risposta è quella di utilizzare definitivamente:
return std::string();
o
return {}; //(c++11)
Anche se a meno che non stanno tornando molto di stringhe vuote nel codice critico delle prestazioni (registrazione suppongo?), la differenza sta per essere ancora insignificante.
Nessuno dei due. Usa 'return {};'. –
E come si riferisce a C? – crashmstr
Questo rientra nel regno della micro-ottimizzazione inutile che il tuo compilatore ottimizzerà usando RVO e copia elision. – CoryKramer