Misusing string concatenations

We still see issues where programmers experience really bad things because they're misusing the str data type. Mainly people complain about poor performance or memory issues when concatenating large strings. So, let me clarify: When strings are concatenated in X++, by doing

myString = myString + "some string"; 

the system needs to find the end of the original string to find out where to copy the string to append and do a lot of copying. In the following example

  1: static void StringMisuse(Args _args)  
 2: {  
 3:     str s;  
 4:     int i;  
 5:     str res;  
 6:     TextBuffer tb = new TextBuffer();  
 7:  
 8:     s = "1234567890";  
 9:  
10:     pause;  
11:     for (i = 1; i <= 100000; i++)  
12:         res = res + s;  
13: //        tb.AppendText(s);  
14:  
15:     print tb.size();  
16:     print strlen(res);  
17:     pause;  
18: } 

running the code using res = res + s takes around 6 minutes on my laptop. Replacing it with the semantically equivalent res += s makes the time barely measurable (at least not with my wristwatch), i.e. a vast improvent in performance. In the first case, a lot of copying of long strings take place, which is expensive. In the second case, far fewer heap operations take place.

You may feel it is advantageous to use the TextBuffer object to do your string manipulations (in this case the time spent in tb.AppendText() to do the concatenations is also barely measurable),

 You may also choose to use strFmt() to construct string. So, instead of

str s = "<" + tagName + " name='" + theName + "'>";

you'd be better off writing

str s = strFmt("<%1 name='%2'>", tagName, theName);

which also happens to be more readable.