This article mainly describes the C # special string type. Have a good reference value, follow the small series together to see it
1. Preface
String is a reference type, does everybody know? But in the process of use, it is found that it still has some characteristics of the value type, which is why?
The reason is. NET considering that if a large number of operations on a string object, when a large number of reference objects to operate, performance is certainly not as good as the value type. NET to improve this performance, provides a dedicated solution: String resident Pool!
2. Text
Let's take a look at the code first:
String str1 = "AA"; String str2 = "a" + "a"; Console.WriteLine (ReferenceEquals (STR1, str2)); Print:true
This str1 and STR2 's memory pointing to the address is actually exactly the same!
The reason is. NET maintains a hash table inside the CLR (which is actually the string dwell pool), where key is the string content, and the value is the address of the managed heap to which it is pointing, and when initialization creates a new string. NET will go to this hash table to search whether there is the same value, if the key is the same, the existing string will be assigned to the address value of the newly created string, if not exist then reassign the address, this is why the above code of memory is true.
Let's look at another piece of code:
String STR3 = "AB"; String STR4 = "a"; STR4 + = "B"; Console.WriteLine (ReferenceEquals (STR3, STR4));//print:false
When false occurs, note the keyword "initialization creation" of the previous column, when the string is created dynamically. NET does not go to the hash table to search whether there is create, but directly create;
If you want to optimize the code above and have more (Xian) high (DE) chasing (Dan) (Teng), we can manually add this string to the string dwell pool for comparison
String STR3 = "AB"; String STR4 = "a"; STR4 + = "B"; STR4 = string. Intern (STR4);//intern: It will search the string-resident pool and return the corresponding address Console.WriteLine if found (ReferenceEquals (STR3, STR4));//print : True
3. Summary
At the end of the string, the following point concludes:
1.string is not created in the CLR with newobj directives, but is created with ldstr instructions! and string has a characteristic of a value type, but in memory it is a reference type, which exists on the managed heap;
2.string is sealed modified, so can not be integrated quilt class;
3. When creating the same content, the string is pointing to the same address, and each action string generates a new address (the constant of string);
4. For a large number of splicing words or use StringBuilder, it is dynamic not like string is constant, but is to create StringBuilder cost is relatively large, so small splicing with string in performance may also be better!
These are the details of the special string type code examples in C #, and more about topic.alibabacloud.com (www.php.cn)!