Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Errrhhh ..... CSharp or VB
Message
From
27/09/2011 05:07:05
 
 
To
27/09/2011 02:04:46
General information
Forum:
ASP.NET
Category:
Other
Miscellaneous
Thread ID:
01524423
Message ID:
01524799
Views:
54
>>
>>AFAIK, there's no point in using a StringBuilder for something like this:
string s = "Tom" + "Dick"+"Harry"+"AsManyMoreAsYouLike"
since you are only assigning to a string once. But, since strings are immutable, if you do this:
string s = "Tom";
>>s += "Dick";
>>s += "Harry";
then you are, in effect, creating a new 's' and discarding the old one with every addition. In that situation using a StingBuilder comes into its own....
>
>
>I'm not so sure, Viv
>
>To me the two above result in pretty much the same, where the first does not assign the intermediate results to s, but the intermediate results are 'calculated' in both cases
>
>Explanation
>
>The + operator is a binary operator, ie takes two operands
>
>The reason that we can write
>
>string s = "Tom" + "Dick"+"Harry"+"AsManyMoreAsYouLike;
>
>is that there is something like associativity which is a convenient way to drop the parentheses.
> I take it that the + operator is left associative, so the expression boils down to
>
>string s = ( ( ("Tom" + "Dick")+"Harry" ) +"AsManyMoreAsYouLike ) ;
>
>
>In prefix notation
>
>string s = +( +(  +("Tom", "Dick"), "Harry") , "AsManyMoreAsYouLike)
>
>
>Which means that in the above case the + operator will be called 3 times with two operands. So it must return intermediate results, which will be stored on the heap since string is a reference type
>
>The two intermediate results
>"TomDick" and "TomDickHarry" will be collected later

Actually I wouldn't be surprised if the compiler optimised it out to
string s = "TomDickHarry";
but I haven't time to check :-{
OTOH if the values weren't literals I think you'd be right.....
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform