Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any issues with using += on a string

Tags:

c#

As the title suggests, is there any reason I shouldn't do the following to append something on to the end of a string:

string someString = "test";
someString += "Test";
like image 242
astro boy Avatar asked Jan 27 '26 04:01

astro boy


1 Answers

If done once, it's no big deal. The content of the two strings is taken, a new string is created and assigned to someString. If you do the above operation many times (for example, in a loop), then there is a problem. For each execution, you're allocating a new object in the heap, a new string instance. That's why it's better to use a buffer-based type, such as StringBuilder, if you have to append content to a string multiple times.

like image 196
Mir Avatar answered Jan 29 '26 20:01

Mir