C#: String and StringBulider

String is a very commonly used type in C#, which can be used to declare strings, and StringBulider can also be used to create a string, so what is the difference between the two.

In fact, String can only be assigned once, which seems strange. We often modify it in normal use without reporting an error, but in fact, the str we modify every time is not the original str but a new one. object, and the original str will become garbage waiting for GC. Both creating new objects and GC will consume resources, so it is unwise to modify string frequently. Here you can see an example:

 string str = "hello";
            Console.WriteLine(str.GetHashCode());
            
            Console.WriteLine( str.ToUpper().GetHashCode());

 

It can be seen that the Hash Code just changes from lowercase to uppercase.

StringBulider is designed to solve this problem. stringBulider can create strings efficiently, because it is an array itself. When changing the content, it will only modify the original one, and will not create new objects, avoiding a lot of waste of resources.

 Here you can see that the hasgcode of two characters is still the same even if one character is added at the end.

Guess you like

Origin blog.csdn.net/m0_61777011/article/details/125373906