C # Program Performance Improvement-1. Analysis of ToString in packing, unpacking, and enumeration

Source: Internet
Author: User

Prospect Abstract: When writing a program, you may accidentally unboxing and unboxing the program code, reducing the efficiency, if loop or Network Program (continuously request processing) occurs in the program, reducing packing and unpacking is a way to improve the efficiency of the program. Not only does it take a long time, but does not accumulate small streams or even rivers and rivers. The optimization starts from the point of view. I. The concept of packing and unpacking: Here is the official definition: http://msdn.microsoft.com/zh-cn/library/yz2be5wk.aspx packing: Value Type → reference type unpacking: Reference Type → Value Type II. Why packing, does the unpacking consume resources (memory and cpu )? 2.1 packing and unpacking: packing. The value type is stored on the memory stack, and the reference type is stored on the memory pair. If you change the defined value type (the data on the stack) to the reference type (stacked), 2.2 text indicates the value type storage in the packing process (no heap issues ): reference type storage (stack stores the address of objects in the heap and actual objects in the heap). If the value type is changed to the reference type, the storage location changes, in case of packing, and in order to unpack, the storage mode of the reference type is not only the storage model of the above reference type, but also the storage of the value type, in this way, you can easily convert it into the corresponding packing type during unpacking. As you can see, the packing is actually better than defining it as a reference type, consuming the memory for the house and increasing the amount of computing (consuming the cpu ). This is an in-depth explanation of the principle level. Only the CLR step can be analyzed. 3. When talking about ToString (), we all know that C # all types of base classes (parent classes) are objects, while in objects, there are just a few methods that can be called subclass inheritance, virtual ToString is one of them. Therefore, all types of c # Have This ToString method. Next, let's talk about one or two of the ToString methods in the case of packing and unpacking. 3.1 for normal value types, Int32 is used as an example (Struct) int a = 123; string B = a. ToString (); is this boxed? A: Value Type → reference type, oh, packing !! Answer: just look at the packing definition, which is indeed in line with the packing definition. However, do not forget that ToString is a virtual method of the base class, and whether the subclass is overwritten. Int account original int (C # Language) → Int32 (CLR, oh is a structure, struct) → extends System. valueType (check the IL code and find it) → extends System. object (this is the ultimate ancestor! Here is ToString.) This is an overwrite of the ToString method in Int32: public override string ToString () {return Number. formatInt32 (this, null, NumberFormatInfo. currentInfo);} the next step is internal implementation. I can't see it? What should I do? By the way, write the code and view the IL code. We can see that there is no packing here! You can use the decompilation tool to view the specific internal implementation, such as ILSpy, reflecter, and ILdasm. 3.2 Enumeration type. Do all value types Use the Tostring method and do not involve the packing operation? This is not all about, but try the enumeration type. Enumeration type, which is a value type. Example: enum TestEnum {Test1, Test2} string test = TestEnum. test1.ToString (); // check whether the packing operation is performed. 3.2.1 check the ToString method in the enumeration. The ToString method public override string ToString () is overwritten () {return InternalFormat (RuntimeType) base. getType (), this. getValue ();} view the implementation of the InternalFormat method private static string InternalFormat (RuntimeType eT, object value) {if (eT. isDefined (typeof (flagsattried), false) {return Internal FlagsFormat (eT, value);} string name = GetName (eT, value); if (name = null) {return value. toString ();} return name;} view eT. isDefined (typeof (flagsattried), false), GetName (), reflection is used here, which may cause performance loss, but there will be no packing operation, but GetName (eT, value ), the value parameter in is the parameter in InternalFormat. Here the parameter is of the object type, while InternalFormat (RuntimeType) base. getType (), this. this. the GetValue method is used to pass this object parameter. Next, you can view the implementation of the GetValue method. We can see that this GetValue method has happened. The packing operation, return (bool) * (sbyte *) ptrRef); this value type, and the returned value required by GetValue is: object Type conclusion: The ToString method in enumeration not only uses the packing operation, but also uses a lot of reflection. To sum up, when enumeration is used, It is very convenient to add several constant states of switch-case for value type operations and not to retrieve the enumerated defined values (ToString, fast. However, we do not recommend that you use the enumerated ToString to obtain the enumerated value. This is very out of date. You can directly use static classes instead (use space for time). 3.3 analyze the technical blog of network Daniel, which was originally packed and unpacked, however, it seems a bit inappropriate to see so many big cows on the Internet! (Don't be scared by their so-called comparison performance) 3.3.1 blog address: http://www.cnblogs.com/XmNotes/archive/2010/09/18/1830355.html this is the first: performance difference 7 thousand times the ToString method blog comment: see the title, the first sentence is, I rely on it! So many people. Times! But when you read the code, you will know what he is doing. var day = DayOfWeek. wednesday; // This is an enumeration. for (int I = 0; I <1000000; I ++) {value = day. toString ();} million-Level Reflection and packing. Do you have such a million-level number and frequent operations? Do you mean you are using this! One is that you directly return a value type week, and finally the presentation layer converts it to you. Even if the packing and unpacking here are two at a time, you can still get millions of clicks! There is also another type similar to yours, which is directly a reference type. If you convert millions of data into static constants like yours. The conclusion is that the example should be based on facts rather than non-conforming things. Different methods and class libraries are used in suitable scenarios. Here not only reflection will take time, packing operation will also cause resource consumption 3.3.2 blog address: http://www.cnblogs.com/yjmyzz/archive/2010/09/19/1830766.html this is the second: also talk about enumeration ToString () Performance Improvement blog explanation: I don't understand what the landlord is doing. The static class you defined has been installed into the static variable dictionary for the first time and is resident in the memory, it will not be released until the program ends. It's similar to reading a million-level static variable cyclically! The ToString method of enumeration is your reflection and packing data of millions of people! I'm dizzy! Does enumeration work like this? If these definitions are commonly used and read at the millions, can you waste some memory! Use this method directly (space for time) public static class EnumLoginError {public static string user name does not exist {get {return "user name does not exist ";}} public static string Password error {get {return "Password error" ;}} the public static string user is locked {get {return "User locked ";}} public static string unknown error {get {return "Unknown error" ;}} the conclusion is: do not do anything superfluous and be skeptical about things. It is also a suitable tool to do the right work, and the right person to do the right thing. 4. Reduce Box Packing. We recommend that you use the Generic set namespace System. Collections. Generic List <T>, which is similar to the upgraded version of ArrayList and ArrayList. Various methods: Sort (), Max (), Min (), Sum ()... Dictionary <K, V> is similar to the upgraded version of Hashtable and Hashtable. T, K, and V are like a lock. The lock set can only store certain types of data. Here, T, K, and V can be other letters.

Related Article

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.