Performance Worries

Use of System.Object as the escape valve to make things as general as possible doesn’t only have bad characteristics with regard to compile-time safety; things are getting very suboptimal on the field of performance, as well. Not only do runtime checks’ needed cast instructions induce additional cost, keeping a value type object as a System.Object causes boxing. Recall how boxing involves wrapping a value in a heap-allocated box, therefore adding pressure to the garbage collector. And when the value needs to be retrieved with its original type, the symmetric unboxing operation occurs. Figure 15.2 illustrates boxing and unboxing.

Figure 15.2. Boxing and unboxing.

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.