返回空字符串:C ++中的有效方法 [英] Returning an empty string : efficient way in c++

查看:76
本文介绍了返回空字符串:C ++中的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种从函数返回空字符串的方法.

I have 2 ways of returning 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?

推荐答案

Gcc 7.1 -O3完全相同,godbolt.org/z/a-hc1d – jterm 4月25日下午3:27

Gcc 7.1 -O3 these are all identical, godbolt.org/z/a-hc1d – jterm Apr 25 at 3:27

原始答案:

进行了一些挖掘.下面是一个示例程序和相关程序集:

Original answer:

Did some digging. Below is an example program and the relevant assembly:

代码:

#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 return {}; (这两个是相同的).

You can see that there is quite a lot more work for the return ""; statement and comparably little for return std::string and return {}; (these two are identical).

正如Frerich Raabe所说的那样,当传递一个空的 C_string 时,它仍然需要对其进行处理,而不仅仅是分配内存.似乎无法对此进行优化(至少不能通过GCC进行优化)

As Frerich Raabe said, when passing an empty C_string, it still needs to do processing on it, instead of just allocating memory. It seems that this can't be optimised away (at least not by GCC)

所以答案是肯定要使用:

So the answer is to definitely use:

return std::string();

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

尽管除非您在性能关键代码中返回很多空字符串(我想是日志记录?),否则差异仍然微不足道.

Although unless you are returning a lot of empty strings in performance critical code (logging I guess?), the difference is going to still be insignificant.

这篇关于返回空字符串:C ++中的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆