Text after "
I have 2 ways to return an empty string from a function.
1)
std :: string get_string () {return ""; }
2)
std :: string get_string () {return std :: string (); }
Which one is more efficient and why?
An example program and related assembly down some digging:
code: < / P>
#include & lt; String & gt; Std :: string get_string1 () {return ""; } Std :: string get_string2 () {return std :: string (); } Std :: string get_string3 () {return {}; } // Thanks Kerek SB Ent Main () {get_string1 (); Get_string2 (); Get_string3 (); }
Assembly:
__ 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 Additional $ 40,% Esp .cfi_def_cfa_offset 8 movl% ebx,% eax popl% ebx .cfi_restore 4 ret $ 4 Cfi_endproc __Z11get_string2v: LFB 738: .cfi_startproc movl 4 (% esp),% eax movl $ __ ZNSs4_Rep20_S_empty_rep_storage E + 12, (% eax) $ 4 rate .cfi_endproc __Z11get_string3v: LFB739: .cfi_startproc movl 4 (% ESP),% eax movl $ __ ZNSs4_Rep20_S_empty_rep_storageE + 12, (% eax) wetting $ 4 .cfi_endproc
it was compiled with the - Std = c ++ 11 -O2
.
You can see that there is enough work to return ;
is very similar to the statement and return std :: string
and return {}
(these two are identical).
Fric Rabe said, when an empty Then the answer is definitely to use: or However, unless you perform are important code return an empty string of many in (logging I think?), The difference is still going to be trivial. C_string , the memory has to still be processed instead of allocating be adapted not that far so (At least not by GCC) looks.
return std :: string ();
return {}; // (c ++ 11)
Comments
Post a Comment