Efficient String Concatenation
-
I have a function that needs to accept a string and append it to another string. I initially implemented it like this:
private String big = "";
...private void OnIncoming( String small )
{
big += small;
big += "\r\n";
}However this seems to be extremely inefficient. Receiving about 300K of text (which happens to come from the net) in small amounts takes about 1 minute. However, if I simply comment out the contents of OnIncoming (the two += lines) it takes about 5 seconds. So it appears the string concatenation is causing the problem. How can I improve this? I need to take a bunch of little strings (one at a time), and concatenate them into a larger string. Any suggestions as to what would be the most efficient way to do this in C#? Thanks in advance for any suggestions, ideas, or assistance!
-
I have a function that needs to accept a string and append it to another string. I initially implemented it like this:
private String big = "";
...private void OnIncoming( String small )
{
big += small;
big += "\r\n";
}However this seems to be extremely inefficient. Receiving about 300K of text (which happens to come from the net) in small amounts takes about 1 minute. However, if I simply comment out the contents of OnIncoming (the two += lines) it takes about 5 seconds. So it appears the string concatenation is causing the problem. How can I improve this? I need to take a bunch of little strings (one at a time), and concatenate them into a larger string. Any suggestions as to what would be the most efficient way to do this in C#? Thanks in advance for any suggestions, ideas, or assistance!
You should use
String.Concat
for up to 4 string parameters,String.Format
if you can format your string, or - which can be used for all - aStringBuilder
(whichString.Format
uses internally). Also, keep in mind that string are immutable while theStringBuilder
is not (meaning it can actually grow). When you concatenate strings, the CLR must get the length of both strings, create a new string of the total length, then copy each character from both strings. You're right - it is very inefficient. The methods and class above will help you (and are nice for formatting and what-not, too).-----BEGIN GEEK CODE BLOCK----- Version: 3.21 GCS/G/MU d- s: a- C++++ UL@ P++(+++) L+(--) E--- W+++ N++ o+ K? w++++ O- M(+) V? PS-- PE Y++ PGP++ t++@ 5 X+++ R+@ tv+ b(-)>b++ DI++++ D+ G e++>+++ h---* r+++ y+++ -----END GEEK CODE BLOCK-----