C # efficient programming topic set 1

Source: Internet
Author: User

Recently, I have discussed a number of topics in group C #'s fast-growing team. I would like to share my summary with you.
Of course, the focus of the so-called topic is to discuss whether it is the best practice or not. If there are any mistakes in the following ideas, you will be overwhelmed.
1: String str1 = "str1" + 9; and String str2 = "str2" + 9. ToString (); which is highly efficient?
We can know that "str1" + 9 "will complete a packing action at runtime. 9. ToString (), no packing behavior occurs. The actual prototype of the ToString () method of Int type is:
Public override String ToString () {return Number. formatInt32 (m_value, null, NumberFormatInfo. currentInfo);} Someone may ask, is that Number in the prototype. what if the FormatInt32 method is packed? The actual Number. FormatInt32 method is an unmanaged method. The prototype is as follows:
[MethodImpl (MethodImplOptions. InternalCall), SecurityCritical] public static extern string FormatInt32 (int value, string format, NumberFormatInfo info );
It directly operates the memory to convert int to string, which is much more efficient than packing.
So the answer is: the latter
Why does packing cause performance loss because there are too many internal problems:
1: first, allocate memory for the value type in the managed heap. In addition to the memory allocated by the value type, the total memory size also includes the type object pointer and synchronous block index;
2: copy the value type to the newly allocated heap memory;
3: return the address of the object that has become the reference type;


2: as, is superior to forced Transformation
The advantage is that as and is do not throw an exception. If the transformation fails, null is returned.

Forced transformation throws an exception, causing the code to handle exceptions with low efficiency.

It is worth noting that as can only transform basic types. For basic types such as int, only forced transformation or is can be used.


3: difference between readonly and const, or better

1: const is static, so it cannot be modified using static; readonly has no such restriction;
2: const can only modify the primitive type; readonly does not have this restriction;
3: const is a constant in the compilation period; readonly is a constant in the runtime period, and its initial value can be set in constructors of the type;
4: After const is compiled, it replaces the variable with the actual value (you can view the IL verification), which is obviously more efficient and can be used in key algorithms. In addition, it has no advantage over readonly.


4: Similarities and differences between the initiator and constructor
The initialization tool is actually a syntactic sugar. After compilation, it is executed at the beginning of the constructor. That is to say, the initiator can be considered as part of the constructor.


5: Precautions for enumeration
1: If the zero value of enumeration is not specified, what will happen;

Static Week week; static void Main (string [] args) {Console. WriteLine (week );}
Even if week is not assigned a value, the zero value is printed.
2: If the same value is specified for the element in the enumeration, what is the problem.

Results that do not match the expected results will be displayed during the equal-type comparison.
3: We recommend that you do not explicitly specify a value for enumeration. However, if enumeration is used for bitwise operations, you must specify an exponential power value of 2 for its elements.


6: Why do all LINQ statements start with from instead of select?
The obvious reason is that for intelligent sensing, to make it take effect when you input a LINQ query, the from clause must be at the beginning; for example:
Var AllCustomers = from Customer in db. Customers
Select new {Customer. ContactName, Customer. Country };


7: dynamic can be used to simplify reflection.
Using Reflection, the caller code is as follows:
DynamicSample dynamicSample = new DynamicSample (); var addMethod = typeof (DynamicSample ). getMethod ("Add"); int re = (int) addMethod. invoke (dynamicSample, new object [] {1, 2 });
After using dynamic, our code looks more concise and reduces the chance of unpacking within a controllable range:
Dynamic dynamicSample2 = new DynamicSample (); int re2 = dynamicSample2.Add (1, 2 );

8: The reason why foreach cannot replace
1: first, add, delete, and delete a set (are all sets? Unknown, but at least most of the sets), the version field of the set will be + 1. foreach adopts the iterator mode, and each iteration should judge whether the version is consistent, if they are inconsistent, an exception is thrown. For does not have such restrictions. Therefore

List <int> list = new List <int> () {0, 1, 2, 3}; foreach (int item in list) {list. remove (item); Console. writeLine (item. toString ());}

Will throw an exception, but will not change to. This is the most important reason why for cannot be replaced by foreach.

2: foreach calls the Dispose method of the Set iterator by default. If the iterator inherits the IDispose method.


9: differences between IComparable and IComparer
The former IComparable <T> provides the default comparator for the class, while the IComparer <T> can provide more comparator for the Collection class. For details, see html ">:

Http://www.bkjia.com/kf/201104/88259.html

 
10: Comparison of advantages and disadvantages of LINQ, comparator, and iterator
To sort and compare data, the traditional method has two problems:
1: The scalability is too low. If new sorting requirements exist, a new comparator must be implemented;
2: The code is too invasive, inheriting interfaces for types, and adding new methods;
For more information, see the blog post.

Http://www.bkjia.com/kf/201104/88258.html

In our own code, we strongly recommend that you use LINQ to bring convenience, but we still need to master the principles of comparator, iterator, and indexer so that we can better understand the idea of LINQ, write code with higher quality.

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.