[Reading Notes] first talk about the benefits of C # programming generic programming

Source: Internet
Author: User

The maximum four benefits of generics are as follows:

1. Performance

Analyze the following example

The add () method of arraylist is defined as an object as a parameter. Therefore, an integer type must be boxed. When reading values in the arraylist, You need to unpack and convert the object to the integer type. Packing and unpacking are easy to use, but the performance loss is relatively high, especially when many items are iterated.

 
Code 1: arraylist list = new arraylist (); list. add (44); // boxing-covert a value type to a reference typeint I1 = (INT) list [0] // unboxing-covert a reference type to a value typeforeach (INT I2 in list) {console. writeline (I2); // unboxing}

 

The list <t> class does not use objects, but defines the type during use. In the following example, the generic type of the List <t> class is defined as int, so the int type is used in the dynamically generated class by the JIT compiler, and no packing or unpacking operations are performed.

 
Code2: List <int> List = new list <int> (); list. add (44); // No boxing-value types are stored in the list <int> int I1 = list [0]; // No unboxing, no cast neededforeach (INT I2 in list) {console. writeline (I2 );}

 

2. type security

It is easy to understand, that is, if the type does not match, an error is returned. Ensure type security

3. BinaryCodeReuse

Generics allow better reuse of binary code. Generic classes can be defined at a time and instantiated with many different types. You do not need to accessSource code.

4. Code Extension

I don't understand what it means.

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.