The difference between string and stringBuilder

1. The string object is constant, and the string represented by the stringBuider object is variable. stringBuilder is an efficient way to create strings in dynamic state provided by .net to overcome the performance impact caused by the constancy of string objects

2. For simple string concatenation operations, stringBuilder is not always better than string in performance. Because stringBuider objects are expensive to create, in the case of fewer string target connections, excessive abuse of stringBuilder will cause performance waste. Only a large number or unpredictable number of string operations should be considered stringBuilder to achieve. In fact, the general connection times are set within 100 times, and there is no difference in performance between the two.

3. When modifying the string information, you are not allowed to create objects at this time, you can use the stringBuilder object. String objects are immutable. Every time you use one of the methods in the System.String class, you must create a new string object in memory, which requires allocating new space for the new object.

string Interning refers to storing strings by maintaining a table. The CLR internally maintains a Hash Table to manage most of the string objects it creates, where the key is the string itself, and the value is the memory address assigned to the corresponding string. public static string Intern(string str); public static string IsInterned(string str); The processing mechanism of both is to find whether the str parameter string exists in the hash table, and if found, it returns a reference to the existing string object. If not found, the Intern method adds the str string to the hash table and returns a reference; the IsInterned method does not add a string to the hash table, but returns null; the StringBuilder object is a dynamic object, allowing it to be expanded The number of characters in the encapsulated string, but you can specify a value for the maximum number of characters it can hold. When the StringBuilder is modified, it will not reallocate space for itself until the capacity is reached. When the capacity is reached, new space is automatically allocated and the capacity is doubled. You can use one of the overloaded constructors to specify the capacity of the StringBuilder class. For example: StringBuilder sb = new StringBuilder(); sb.Append("a") He does not frequently apply for memory space, he will automatically expand backwards.

Guess you like

Origin blog.csdn.net/Charles_hui/article/details/109282637