Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does returning a indirect typed object affect performance?

Tags:

c++

I have an inline function

string myFunction() { return ""; }

Compared with

string myFunction() { return string(); }

does it has a performance sacrifice?

Tested it on VC2012 release with std::string and QString (although on QString, the two returns different results : thanks to DaoWen). Both show the second version is about 3 times faster than the first. Thanks to all your answers and comments. Tested code is attached below

#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;
}
like image 979
user1899020 Avatar asked Oct 24 '13 13:10

user1899020


3 Answers

They will each cause different std::string constructors.

The std::string() -- will create an empty object.

The "" will construct using std::string(char*)

The later will internally do a strlen+strcpy which is not needed in the first, so very small difference.

like image 158
Soren Avatar answered Nov 08 '22 20:11

Soren


In the example you posted, return ""; will be automatically translated to return string(""); at compile time. Unless string("") is significantly slower than string(), then there shouldn't be much of a difference.


In your comment you mention that you're actually using QString, not std::string. Note that QString() constructs a null string (isNull() and isEmpty() both return true), whereas QString("") constructs an empty string (isEmpty() returns true but isNull() returns false). They're not the same thing! You can think of QString() like char * str = NULL;, and QString("") like char * str = "";.

like image 45
DaoWen Avatar answered Nov 08 '22 19:11

DaoWen


Use return string(); as that will use the default constructor. A good Standard Library implementation will probably not even initialise the string buffer at that point.

The constructor from const char* must take a string copy. So I think return ""; will be slower.

But, to be really sure, race your horses.

like image 1
Bathsheba Avatar answered Nov 08 '22 21:11

Bathsheba