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;
}
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.
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 = "";
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With