On Thu, 2005-02-10 at 18:48 +0100, Chateauneu Remi wrote:
I'm working on an application with many std::string concatenations, everywhere. This is consuming a lot of CPU resources, due to temporary strings, memory allocation, etc... Due to the size of the existing code, it is not possible to make big changes.
I tried first to transform these kind of expressions: std::string a = b + c + d + e ;
... into ...
std::string a(b); a += c ; a += d ; a += e ;
It's a little ugly, but you can do std::string a; a.reserve (b.size () + c.size () + d.size ()); a += b += c += d;
... and it is definitively faster, but not enough.
I've then worked on a method, just by adding a special object after the '=' sign, which transforms these concatenations into a two pass operation, the first to calculate the total length and allocate the destination string, and the second pass to actually copy the source strings into the destination.
One just need to re-write the concatenations this way : std::string a = my_special_object() + b + c + d + e ;
But maybe I am reinventing the wheel. Is there in Boost, a way to speed up this kind of operation ?
I'm not aware of anything in boost - the string algo lib seemed like a
natural place but I didn't see anything.
I wrote something like that. I'm not sure if it's really safe and
correct and all - I believe the temporary lifetime relied on is
guaranteed ....
You can write:
std::string s1;
s1 << concat () + a + b + c;
or
std::string s2 = concat () + a + b + c;
I'm not really sure it's worth the obfuscation factor, but if you want
to see it, let me know. It's not complicated, but there's probably more
than one way to skin the cat.
--
t. scott urban