Explore the immutable data types of C #

Source: Internet
Author: User

Read the catalogue:

    1. Immutable objects
    2. Customizing immutable Collections
    3. NET provided immutable collections
    4. Immutable advantages
    5. Immutable Object Disadvantage
Immutable objects

Immutable (immutable): Once an object has been created, their values cannot be changed, and each subsequent change will result in a new object.

var str="mushroomsir"; str. Substring (06)

The string in C # is immutable, and Substring (0, 6) returns a new string value, and the original string is unchanged in the shared domain. Another StringBuilder is variable, which is also the reason for recommending the use of StringBuilder.

var age=

When the memory that stores the value 18 is allocated to the age variable, its memory value cannot be modified.

age=2;

A new value of 2 is assigned to the age variable in the stack, and the value in the memory of 18 cannot be changed, and int is immutable in C #.

classcontact{ Public stringName {Get;Set; }  Public stringAddress {Get;Set; }  PublicContact (stringContactName,stringcontactaddress) {Name=ContactName; Address=contactaddress; }}   varmutable =NewContact ("er Mao","Tsinghua"); mutable. Name="Mao"; mutable. Address="Peking University";

We instantiate the Mutablecontact assignment to mutable, and then we can modify the Mutablecontact object's internal field value, which is no longer the initial value, and can be called a variable (mutable) object.

mutable objects are shared in multi-threaded concurrency, and there are some problems. Multithreaded under a thread assignment to Name = "Da Mao" This step, the other threads have the potential to read the data is:

  " Mao " ;   " Tsinghua ";

It is clear that this data integrity is not guaranteed, there is also called data tearing. We change mutable objects to immutable objects as follows:

 Public classcontact2{ Public stringName {Get;Private Set; }  Public stringAddress {Get;Private Set; } PrivateContact2 (stringContactName,stringcontactaddress) {Name=ContactName; Address=contactaddress; }     Public StaticContact2 CreateContact (stringNamestringaddress) {        return NewContact2 (name, address); }}

The name and address fields can only be initialized using the Contact2 constructor. Contact2 is an immutable object at this point because the object itself is an immutable whole. You can use immutable objects without worrying about data integrity, ensuring data security, and not being modified by other threads.

Customizing immutable Collections

When we go to enumerate mutable collections, we often need to lock in for thread-safe purposes, preventing the collection from being modified in other threads, and using immutable collections to avoid this problem. The data structures we use in our usual way are implemented in variable mode, so how do we implement an immutable data structure? The example of the stack, the code is as follows:

 Public InterfaceIstack<t>: ienumerable<t>{istack<T>Push (T value); Istack<T>Pop ();    T Peek (); BOOLIsEmpty {Get; }} Public Sealed classStack<t>: istack<t>{    Private Sealed classEmptystack:istack<t>    {         Public BOOLIsEmpty {Get{return true; } }         PublicT Peek () {Throw NewException ("Empty Stack"); }         PublicIstack<t> Push (T value) {return NewStack<t> (Value, This); }         PublicIstack<t> Pop () {Throw NewException ("Empty Stack"); }         PublicIenumerator<t> GetEnumerator () {yield  Break; } IEnumerator Ienumerable.getenumerator () {return  This. GetEnumerator (); }    }    Private Static ReadOnlyEmptystack empty =NewEmptystack ();  Public StaticIstack<t> Empty {Get{returnempty;} }    Private ReadOnlyT Head; Private ReadOnlyIstack<t>tail; PrivateStack (T head, istack<t>tail) {         This. Head =Head;  This. Tail =tail; }     Public BOOLIsEmpty {Get{return false; } }     PublicT Peek () {returnHead;}  PublicIstack<t> Pop () {returntail;}  PublicIstack<t> Push (T value) {return NewStack<t> (Value, This); }     PublicIenumerator<t>GetEnumerator () { for(Istack<t> stack = This;!stack. IsEmpty; stack =stack. Pop ())yield returnstack.    Peek (); } IEnumerator Ienumerable.getenumerator () {return  This. GetEnumerator (); }}
View Code
    • A new stack object is instantiated when the stack is entered
    • The new value is passed through the constructor and stored in the new object head position, where the old stack object is placed in the tail position reference
    • The Stack object that returns the tail reference of the current stack object when it is out of the stack

Here's how to use it:

 istack<int  > S1 = Stack<int  >. Empty;istack  <int  > s2 = S1. Push (10   <int  > s3 = s2. Push (20   <int  > S4 = S3. Push (30   <int  > V3 = S4. Pop ();  foreach  (var  item in   S4) { // dosomething } 

Each push is a new object, and the old object cannot be modified so that the enumeration collection does not have to worry about other threads being modified.

NET provided immutable collections

Immutable queues, immutable lists and other data structures if you do it yourself, it's a little big. Fortunately, net has provided the base Class library for immutable collections in version 4.5. To install with NuGet:

Install-package Microsoft.Bcl.Immutable

Use the following, almost as we have defined above:

        immutablestack<int> a1 = immutablestack<int>. Empty;        Immutablestack<int> a2 = A1. Push (ten);        Immutablestack<int> a3 = A2. Push (a);        Immutablestack<int> a4 = a3. Push (+);        Immutablestack<int

Using the net immutable list collection One thing to note is that when we push a value, we re-assign it to the original variable, because a new object is generated after push, and the original A1 is just the old value:

   immutablestack<int> a1 = immutablestack<int>. Empty;   A1. Push (// Incorrect , A1 is still a null value, Push generates a new stack.)    a1 = A1. Push (// need to reassign new stack to A1

NET provides common data structures

    • Immutablestack
    • Immutablequeue
    • Immutablelist
    • Immutablehashset
    • Immutablesortedset
    • Immutabledictionary<k, v>
    • Immutablesorteddictionary<k, v>

The difference in the complexity of the algorithm for immutable and mutable collections:

Immutable advantages
    • Collection sharing security, never changed
    • Lock collection is not required when accessing a collection (thread safe)
    • Modify the collection without worrying about the old collection being changed
    • Write more concise, functional style. var list = ImmutableList.Empty.Add (10). ADD (20). ADD (30);
    • Ensure data integrity, security
Immutable Object Disadvantage

The advantage of immutable itself is that it is a disadvantage when each object/collection operation returns a new value. The old values remain for a while, which can make the memory much more expensive, and can also cause the GC to be recycled, with more performance than a mutable set.

Like string and Stringbuild, the immutable collection provided by NET also increases the API for bulk operations to avoid creating objects in large numbers:

     immutablelist<string> Immutable = immutablelist<string>. Empty;         // Convert to a collection        of batch operations var immutable2 = immutable. Tobuilder ();        Immutable2. ADD ("xx");        Immutable2. ADD ("xxx");         // revert to immutable collection        immutable = Immutable2. Toimmutable ();

Let's compare the performance of a mutable collection, an immutable builder collection, an immutable collection, and add a new object 1000W times:

The comparison code is as follows:

   Private Static voidList () {varList =Newlist<Object>(); varSP =stopwatch.startnew ();  for(inti =0; I < +*10000; i++)            {                varobj =New Object(); List.            ADD (obj); } Console.WriteLine ("mutable List collection:"+sp.        Elapsed); }              Private Static voidbuilderimmutablelist () {varList = immutablelist<Object>.            Empty; varSP =stopwatch.startnew (); varblist=list.            Tobuilder ();  for(inti =0; I < +*10000; i++)            {                varobj =New Object(); Blist.            ADD (obj); } list=list.            Toimmutable (); Console.WriteLine ("Immutable Builder List collection:"+sp.        Elapsed); }        Private Static voidimmutablelist () {varList = immutablelist<Object>.            Empty; varSP =stopwatch.startnew ();  for(inti =0; I < +*10000; i++)            {                varobj =New Object(); List=list.            ADD (obj); } Console.WriteLine ("Immutable List collection:"+sp.        Elapsed); }
View Code

Another disadvantage is more interesting, and many people ignore it. Because of the immutable nature of string, we need to pay special attention when we use string to save sensitive information.
For example, the password var pwd= "Mushroomsir", at this time the password will be stored in clear text in memory, you may later encrypt the empty, etc., but this will generate new values. While the plaintext is stored in shared domain memory, anyone who can get the dump file can see the plaintext, increasing the risk of password theft. Of course this is not a new problem, NET2.0 provides securestring for secure storage, recovery and cleanup when used.

IntPtr addr = marshal.securestringtobstr (secureString); string temp = marshal.ptrtostringbstr (addr); Marshal.zerofreebstr (addr); WriteProcessMemory (...)

Explore the immutable data types of C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.