Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type and performance

I'm wondering if using generic types through out the program will have any (significant)degrading performance effect on the application. I use a lot of collection objects(lists, sets, maps) and to give better flexibility to the application(this application has to be integrated into other application) I used only generic types instead of parameterizing them. Is this a common practice or does anyone have a suggestion/advice? Will there be any significant performance degrade?

Thanks in advance,

like image 951
Ozyman Avatar asked Feb 08 '11 10:02

Ozyman


2 Answers

There will be no performance degradation at all, because generics are effectively a "compile-time trick".

The compiler uses this information to reject certain type-unsafe practices that would otherwise appear at runtime, if not using generics. During runtime only the raw classes (i.e. the upper bound of the generic parameters) are used, so the performance will be identical to not using generics, and just casting the classes yourself.

like image 144
Andrzej Doyle Avatar answered Sep 27 '22 16:09

Andrzej Doyle


As explained by other contributors, in most cases, using generics will not have any impact on performances. The only performance issue is when you have to replace a primitive type by its object type (for example, if you need to pass int as a generic parameter.

However, unless if you make an intensive usage of your object, the performance penalty is not visible. Consequently, you should start with generic and, if a performance issue due to this particular case occur, you can still replace your generic object by a class that use the primitive type. Early optimisation is evil.

like image 20
Nicolas Avatar answered Sep 27 '22 16:09

Nicolas