C #, String and StringBuilder difference

     First of all make it clear that, String is a reference type, String str = null. And you want to know the value of String is immutable. Why value of String immutable? This place I checked online, there is no good answer, and then add After finding the back.

String immutability of example: String a = "123"; a + = "45"; this time you might think, the value of a clearly become a "123456" but the reality is this. The first string a = "123"; allocated on the heap memory, stores a value "123", where a just a memory address, pointing to the heap, "123",

When a + time = "45", is assigned in a heap memory, storage, "12345", this time is only a point to one object becomes "12345" address. So the value of a change every occurrence, in fact, is a value added, before "" 123 "did not disappear. So when doing string concatenate strings, especially for recycling, the use of such a + =

When the syntax will be adhered to a lot of memory loss. This time it is recommended to use a StringBuilder object. StringBuilder stitching does not create a new memory space.

  Is a string concatenation can StringBuilder classes, can specify a length stringBuilder object initialization, StringBuilder has a property of type int Capacity for stringBuilder specified length of the container. A StringBuilder Append (string str) splicing method for a string, and the string length can be detected automatically, when the previously specified length exceeds the maximum length, it will automatically increase the length of a capacity. So during a lot of string concatenation, you should use StringBuilder object.

 

 

Guess you like

Origin www.cnblogs.com/Echolh/p/11901412.html