返回间接类型对象会影响性能吗?

use*_*020 7 c++

我有一个内联函数

string myFunction() { return ""; }
Run Code Online (Sandbox Code Playgroud)

和....相比

string myFunction() { return string(); }
Run Code Online (Sandbox Code Playgroud)

它有性能牺牲吗?

使用std :: string和QString在VC2012版本上测试它(虽然在QString上,两者返回不同的结果:感谢DaoWen).两者都显示第二个版本比第一个版本快3倍.感谢您的所有答案和评论.测试代码附在下面

#include <iostream>
#include <string>
#include <ctime>
using namespace std;

inline string fa() { return ""; }
inline string fb() { return string(); }

int main()
{
    int N = 500000000;
    {
        clock_t begin = clock();
        for (int i = 0; i < N; ++i)
            fa();
        clock_t end = clock();
        double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
        cout << "fa: " << elapsed_secs << "s \n";
    }

    {
        clock_t begin = clock();
        for (int i = 0; i < N; ++i)
            fb();
        clock_t end = clock();
        double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
        cout << "fb: " << elapsed_secs << "s \n";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Dao*_*Wen 1

在您发布的示例中,将在编译时return "";自动翻译为. 除非明显慢于,否则应该不会有太大差异。return string(""); string("")string()


在您的评论中,您提到您实际上正在使用QString,而不是std::string。请注意,QString()构造一个空字符串isNull()并且isEmpty()都返回 true),而QString("")构造一个空字符串isEmpty()返回 true 但isNull()返回 false)。它们不是同一个东西!你可以想到QString()喜欢char * str = NULL;QString("")喜欢char * str = "";