I wanted to know if there are any run time advantages to Generics provided from 开发者_如何学CJava5. I mean, I know that we can achieve type safety for classes/collections and allow a range of possible objects for a generic, but are there any benefits that we get at Run time ahead of compilation time?
Java generics are removed at runtime via erasure, so the performance should be identical.
Some information about them is available through reflection (say in http://download.oracle.com/javase/6/docs/api/java/lang/reflect/Constructor.html#getTypeParameters%28%29 ) but they don't make your programs run better.
CoolBeans, I took him to mean "beyond" compilation time benefits.
Yes - but it's very minor.
When you use generics, you don't need to use instanceof
and casting everywhere, so the bytecode instructions that do type checking for those instructions are no generated. On the downside, you can wind up with some fairly low-level errors at runtime if you link to old versions of your classes without recompiling them.
Still, if you heavily use a tight loop that otherwise needs a cast, then I suppose generics might speed things up a tiny, tiny bit. But performance improvement is not the point of using them.
精彩评论