More effective C# – Generics

Generics in C# – JIT

  • The JIT compiler creates one machine code version of a generic class for all reference types
  • List<MyClass> myList = new List<MyClass>();
    List<File> files = new List<File>();
    List<string> strings = new List<string>();
    

    The C# compiler enforces type safety at compile time, and the JIT compiler can produce a more optimized version of the machine code by assuming that the types are correct.

  • Different rules apply to closed generic types that have at least one value type used as a type parameter
  • List<MyClass> myList = new List<MyClass>();
    List<File> files = new List<File>();
    List<int> numbers = new List<int>();
    

    Generic types that will be used with multiple different reference types do not affect the memory footprint. All JIT-compiled code is shared. However, when closed generic types contain value types as parameters, that JIT-compiled code is not shared

  • There is, however, a plus side to using generics with value type parameters: You avoid all boxing and unboxing of value types, thereby reducing the size of both code and data for value types

 

Bibliography

  • More Effective C# – 50 Specific Ways To Improve C#
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s