Hi
I realise StringBuilder is generally better for building strings
dynamically, but for a fixed string built over a number of lines, would the
compiler recognise that the following could be represented as a single
string and optimise out reallocations?
Example
string myString = "Blah";
myString += "Blah";
myString += "Blah";
myString += "Blah";
myString += "Blah";
Thanks
Glenn
Phill W. - 04 Jul 2006 13:30 GMT
> would the compiler recognise that the following could be represented
> as a single string and optimise out reallocations?
[quoted text clipped - 4 lines]
> myString += "Blah";
> myString += "Blah";
Try it and see - the ILDasm utility is your friend in this - but my
/guess/ is that it won't.
You could, of course, rewrite the above as ...
string myString
= "Blah"
+ "Blah"
+ "Blah"
+ "Blah"
+ "Blah" ;
... which the compiler /does/ optimise - at least the equivalent
construct in VB.Net gets optimised so the C# compiler d*** well ought to
as well.... ;-)
HTH,
Phill W.
Jon Skeet [C# MVP] - 04 Jul 2006 18:43 GMT
> I realise StringBuilder is generally better for building strings
> dynamically, but for a fixed string built over a number of lines, would the
[quoted text clipped - 8 lines]
> myString += "Blah";
> myString += "Blah";
I don't believe it does - but if you write it as:
string myString = "Blah"
+"Blah"
+"Blah"
+"Blah"
+"Blah";
then the concatenation will be done at compile time.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too