Does an indirect typed object return performance?

I have a built-in function

string myFunction() { return ""; } 

Compared with

 string myFunction() { return string(); } 

Does the victim have performance?

Tested it on the VC2012 release using std :: string and QString (although on QString they return different results: thanks to DaoWen). Both show that the second version is about 3 times faster than the first. Thanks to all your answers and comments. The 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; } 
+7
c ++
source share
3 answers

In the above example, return ""; will be automatically translated to return string(""); at compile time. If string("") significantly slower than string() , then there should not be much difference.


In your comment, you mentioned that you are actually using QString , not std::string . Note that QString() builds an empty string ( isNull() and isEmpty() both return true), while QString("") creates an empty string ( isEmpty() returns true, and isNull() returns false). This is not the same thing! You can think of QString() as char * str = NULL; and QString("") as char * str = ""; .

+1
source share

They will call different constructors std :: string.

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

"" will be built using std :: string (char *)

Later it will internally do strlen + strcpy, which is not needed in the first, so there is very little difference.

+3
source share

Use return string(); because it will use the default constructor. A good implementation of the standard library probably does not even initialize the string buffer at this point.

The constructor from const char* should take a lowercase copy. Therefore, I think return ""; will be slower.

But to be sure, rock your horses.

+1
source share

All Articles