Just trying to get my head around Generics by reading this enlightening article by Juval Lowy
Paraphrasing.. When you define a Generic class definition, it is compiled into IL.
- For value-types, as soon as you request for a specific value-type, it substitutes the T with your specific value type to obtain the IL for that specific configuration e.g.
MyList<int>
Benefit: No boxing and unboxing penalties. - All good.. for reference types, the compiler replaces all instances of T in your definition with Object and creates the IL which is used for all ref types. Instances however are allocated based on the actual requested ref type e.g.
MyList<String>
Now pre-generics we could have written methods that take Object
parameters. Generics claims 100% performance improvement because 'it avoids the performance penalty you incur when you downcast the object type to your specific type when you want to use it'
// assume GetItem returns an Object
string sMyPreciousString = (string) obList.GetItem();
What is this performance hit when you downcast from Object to specific reference type? Also it seems like up-casting to Object (even Generics would do this) isn't a performance hit.. why?