Using "+=" to Concat
So often I end up doing this...:
String newStr = "";
if (
...for many, many properties. When actually compiled, every time the "+=" concatenation is used, an entirely new string must be created to hold the 'new' complete string. This can become very inefficient and slow if you do a large number of such string concats.
Using StringBuilder
What I didn't know about, was the StringBuilder class. Found under the System.Text library, StringBuilder maintains an internal buffer to which [via the function StringBuilder.Append(
Thus the usage of StringBuilder *CAN* be more efficient then using "+=". Note that more overhead is needed to create and manage the StringBuilder object, so in all cases, StringBuilder will *NOT* be absolutely more efficient. It really depends on the size of the strings and the frequency of the concats.
General Rule of Thumb
If the concats can fit into one statement [or only a few statements], then the "+=" is probably the safest route to take. - If you have multiple long, or a dynamic amount of string concats, then StringBuilder may be able to increase efficiency.
Reference: www.yoda.archsys.com
No comments:
Post a Comment