www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - string concatenation overhead

reply mandel <oh no.es> writes:
I have a function call like this:
foo("abc" ~ str1 ~ "123" ~ str2 ~ "xyz");

Afaik, the whole string would be copied on every concatenation.

An ugly improvement would be:
char[] tmp = "abc";
tmp ~= str1;
tmp ~= "123";
tmp ~= str2;
tmp ~= "xyz";
foo(tmp);
Even faster would be preallocation (tmp.lengh == needed; tmp.length = 0).

Is the first case optimized by the compiler already?
Or do we have to go the ugly way to avoid redundant copies?
Nov 28 2007
parent "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"mandel" <oh no.es> wrote in message news:fikq77$25he$1 digitalmars.com...
I have a function call like this:
 foo("abc" ~ str1 ~ "123" ~ str2 ~ "xyz");

 Afaik, the whole string would be copied on every concatenation.

 An ugly improvement would be:
 char[] tmp = "abc";
 tmp ~= str1;
 tmp ~= "123";
 tmp ~= str2;
 tmp ~= "xyz";
 foo(tmp);
 Even faster would be preallocation (tmp.lengh == needed; tmp.length = 0).

 Is the first case optimized by the compiler already?

Yes.
Nov 28 2007