vendredi 30 janvier 2015

Optimizing string creation

I have the following mock up code of a class which uses an attribute to set a filename:



#include <iostream>
#include <iomanip>
#include <sstream>

class Test {
public:
Test() { id_ = 1; }
/* Code which modifies ID */

void save() {
std::string filename ("file_");
filename += getID();
std::cout << "Saving into: " << filename <<'\n';
}

private:
const std::string getID() {
std::ostringstream oss;
oss << std::setw(4) << std::setfill('0') << id_;
return oss.str();
}

int id_;
};

int main () {
Test t;
t.save();
}


My concern is about the getID method. At first sight it seems pretty inefficient since I am creating the ostringstream and its corresponding string to return. My questions:


1) Since it returns const std::string is the compiler (GCC in my case) able to optimize it?


2) Is there any way to improve the performance of the code? Maybe move semantics or something like that?


Thank you!


Aucun commentaire:

Enregistrer un commentaire