0

I have string that i need to combine with another string , for example

string string1 = "cars"; // the text is just for example 
string string2 = "white";
// then
string string1 = string1 + string2;
// or
string string1 += string2;

Alright , at first glance it doesn't have any problem right ? NOPE , it does have problem

when the string.length / the string contain A LOT OF CHARACTER , for example when it contain 100.000 word , it start to get laggy or freeze when i put it inside loop, because it need to copy 100.000 word plus word from the other string everytime it combines string1 with string2 .

Is the any alternative way to add new text to string that contain massive amount of word ?

1 Answers1

6

The correct way to accumulate strings in c# is using StringBuilder. Example:

StringBuilder sb = new StringBuilder();
sb.Append("...");
sb.Append("...");
....
var result = sb.ToString()

Your solution appear to lag, since every time you "modify" a string a brand new one is created instead, so the garbage collector get a little crazy...

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115