C # copy the value behind the code

Source: Internet
Author: User
Tags mscorlib
A kind of frequently used packing
 
Int32 I = 100; console. writeline ("the number is:" + I );

Use the Il dasm tool in vs SDK tools to check the generated IlCode:

. method private hidebysig static void main (string [] ARGs) cel managed {. entrypoint // code size 27 (0x1b ). maxstack 2. locals Init ([0] int32 I) il_0000: NOP il_0001: LDC. i4.s 100 il_0003: stloc.0 il_0004: ldstr "The number is:" il_0009: ldloc.0 il_000a: Box [mscorlib] system. int32 il_000f: Call string [mscorlib] system. string: Concat (object, object) il_0014: Call void [mscorlib] system. console: writeline (string) il_0019: NOP il_001a: Ret} // end of method program: Main 

You can find that there is a box packing operation in row il_000a. this is mainly because the console. the writeline method outputs a string. In this case, we enter the formula with the + sign, which calls the string. concat (Object arg0, object arg1) method, so the int32 data is packed into an object data.

To complete packing

1. newly allocated managed heap memory (size: Value Type instance size plus a method table pointer and a syncblockindex)

2. Copy the value type instance field to the newly allocated memory.

3. Return the reference address of the newly allocated object in the managed heap.

Avoid packing like this

Packing is like packing an item. It takes a little time. The Packing Time of the above Code is negligible, but if such code appears in a loop with a large number of times, you need to improve it. but it is easy to avoid such packing. Change the above two lines of code to the following:

 
Int32 I = 100; console. writeline ("the number is:" + I. tostring ());

The Code simply converts int32 to a string type (reference type). Some people suspect that the tostring () method will be packed once, because they think I is a value type, string is a reference type. however, you can check the Il code generated by these two statements to see if the packing has occurred:

 
. Method private hidebysig static void main (string [] ARGs) cel managed {. entrypoint // code size 28 (0x1c ). maxstack 2. locals Init ([0] int32 I) il_0000: NOP il_0001: LDC. i4.s 100 il_0003: stloc.0 il_0004: ldstr "The number is:" il_0009: ldloca. s I il_000b: Call instance string [mscorlib] system. int32: tostring () il_0010: Call string [mscorlib] system. string: Concat (string, string) il_0015: Call void [mscorlib] system. console: writeline (string) il_001a: NOP il_001b: Ret} // end of method program: Main

We can find thatThe tostring () method does not produce any Box Packing operations.Only the string representation of the value obtained by the value type.

Conversion between value type and reference type

When you use the new keyword to create a reference type object, this object is always in the managed heap, and the returned pointer to this object.Each time you create an instance of the reference type, you need to allocate memory from the managed heap. The garbage collection mechanism manages the memory. If each type is managed like this, this mechanism willProgramPerformance has some negative impact, soFor simple types that are frequently used, CLR classifies them as value types and distributes them on the stack..

All referred to as "classes" are reference types!Pay special attention to system. string is also a class, which is also a reference type. Because of a "string resident" technology, it becomes a "reference type with value type characteristics ".Both the structure and enumeration types are value types.For example, int32 is just a struct.

Because the value type is not affected by the garbage collection mechanism, it can achieve better performance in some cases. however, if a value-type instance is often called by a class, such as being put into a list <t> or another set (also a class), the program will open up another memory, copy the value of this value type instance to the memory... This will affect the performance.

Therefore, I personally think that the value has been copied in the following two cases, and we do not want this to happen:

1. the parameter type passed by the method is object type. of course, this approach is to be compatible with other types of parameters, but you can avoid a value type-> object type operation by reloading this method.

2. The value type data is used by a class.

When the memory is released

Variables of the value type are automatically released after the scope ends, and the reference type must be released through the garbage collector.

However, stream is also a class. The instances it generates are managed by the managed code, and the garbage collection mechanism is available to recycle its resources (memory. but we still need to enter xxstrean. close () and xxstream. dispose () is caused by uncertainty in memory collection. if xxstream is not written. dispose (), CLR does recycle its resources at a certain time, but for the following two reasons, we need to enter xxstream. dispose ():

1. For the stream class, memory resources are relatively limited and need to be released in a timely manner. Other resources, such as those connected to the network, need to be released.

2. Most of the resources opened by stream are exclusive. If other code tries to open this resource again before it is released, an exception will be thrown.

Of course, if I think it is annoying to write xxstrean. Close () and xxstream. Dispose (), C # provides the usage of the using statement block:

Using (filestream FS = new filestream (......)){//......}

The FS in the above Code will be promptly released before the using statement block ends. Of course, the objects in the () following using need to implement the idisposable interface, which provides the dispose () method.

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.