Returning an empty string : efficient way in c++ -


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 C_string , the memory has to still be processed instead of allocating be adapted not that far so (At least not by GCC) looks.

Then the answer is definitely to use:

  return std :: string ();  

or

  return {}; // (c ++ 11)  

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.


Comments