Assuming that we have a dummy function `foo(const String& s)`, this code is more efficient
Code: Select all
int i = 42;
float f = 0.23f;
foo(String() << "Some value : " << i << ", another one : " << f)
Code: Select all
int i = 42;
float f = 0.23f;
foo("Some value : " + i + ", another one : " + f)
Another example, when using string in loops. Assuming we have a list of string (std::vector<String>), merely a list of filename to load
Code: Select all
for (std::vector<String>::const_iterator i = l.begin(); i != l.end(); ++i)
{
String absoluteFileName = path + *i;
// Do something
}
Code: Select all
String absoluteFileName;
const std::vector<String>::const_iterator end = l.end();
for (std::vector<String>::const_iterator i = l.begin(); i != end; ++i)
{
absoluteFileName.clear();
absoluteFileName << path << *i;
// Do something
}
The worst scenario : 2 malloc + 1 free for the first example, (N+1) malloc + (N+1) free where N = l.size() (+1 for the use of the operator +)