Generics performance concerns? Don't sweat it!

Sahil points to the #2 bug report on the MSDN Product Feedback center regarding concerns over the performance of generics. My feelings on this pretty much echo an earlier post I made about performance in general.

Who cares if generics are 1000 or 10000 times slower (which I don’t believe – it might be for first call while the type is dynamically generated and compiled if necessary, but after that the difference should be small)? What matters is whether the performance of your application as a wholeis sufficient and meets your specifications. People make this mistake all the time, worrying about the overhead of every instruction, when the real performance of whole applications is usually determined by network/file/database I/O or particular computational processes. That is where you worry about performance – at the places where you have identified through measurement that it needs to be addressed. Everywhere else, do what makes the most sense for maintainable code – and the type safety and reduction of repetitive code declarations provided by generics are huge from that perspective.



Bottom line is that even if it is 1000 times slower across the board , I don’t believe that will have a significant impact on the overall performance of most apps that will use generics. You also have to be very careful about making claims like this without substantiating them with actual measurements and the situations under which the measurement was performed. I bet I can set up a loop with a generic collection and an untyped collection of value types where the generic collection would beat the pants off the non-generic collection due to all the boxing/unboxing that has to occur getting those value types in and out through object references. Does that mean that generics are XX times faster than non-generics? No, it means that in one particular scenario (which is probably an immeasurable fraction of the overall computing time of the application) there is a measurable benefit of using one approach over another.



Bottom line: Genericshave huge benefit. You should plan to use them anywhere you want type safety and don’t want to reinvent the wheel. If you have implemented something with them and have MEASURED that to be a bottleneck for performance in your application, then optimize that code… possibly removing the generics. But please people don’t start preaching that it is a “best practice“ not to use generics because of “performance“. Ugh.