On Jun 28, 2012, at 4:10 AM, Matthew Leibowitz wrote:
> Although this won't solve your problem, string + string is a bad practice. It
> is better to use a StringBuilder:
string.operator+() _may_ be a bad practice. In this case, it is NOT a bad
practice; it is fine.
Specifically, StringBuilder is amortized O(n), so it may need to resize the
internal buffer, allocating more memory.
string.operator+, on the other hand, has two compiler features:
1. String constants are concatenated at compile-time. This expression:
"a" + "b" + "c"
is translated by the compiler into:
"abc"
2. When concatenating non-constant strings, all of them are passed to
string.Concat() at once, and string.Concat() is able to allocate a buffer large
enough to store _all_ the strings at once, no resize needed. This expression:
Name + "\n" + Unit + "\n" + AddressLine1
is generated as:
string.Concat (Name, "\n", Unit, "\n", AddressLine1)
StringBuilder will ~always have "slack"/extra memory involved. String.Concat()
never will...for the expression it's involved with.
Thus the real question when comparing string.operator+ to StringBuilder is
whether you have "intermediate named temporaries," for example with loops. If
you're using a (non-compiler-generatd) "temporary" variable, you should
normally prefer StringBuilder;
// BAD
string val = "";
for (int i = 0; i < 1000; ++i)
val += i + " ";
return val;
// GOOD
var sb = new StringBuilder();
for (int i = 0; i < 1000; ++i)
sb.Append (i).Append (" ");
return sb.ToString ();
- Jon
_______________________________________________
Monodroid mailing list
[email protected]
UNSUBSCRIBE INFORMATION:
http://lists.ximian.com/mailman/listinfo/monodroid