Saturday, February 14, 2004

Problems with Java Generics

Generics in C#, Java, and C++ "...with Java generics, you don't actually get any of the execution efficiency that I talked about, because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. So the compiled image for List is like a List where you use the type Object everywhere...Of course, if you now try to make a List, you get boxing of all the ints. So there's a bunch of overhead there. Furthermore, to keep the VM happy, the compiler actually has to insert all of the type casts you didn't write."

"When you apply reflection to a generic List in Java, you can't tell what the List is a List of. It's just a List. Because you've lost the type information, any type of dynamic code-generation scenario, or reflection-based scenario, simply doesn't work."

With 1.3 casting used to be a fairly big overhead, with 1.4 this isn't an issue. Running the trove4j benchmarks in 1.4 you can still see the performance difference of objects vs primitives.

The second issue, and it's the same with autoboxing, seems to highlight how the syntax gives the illusion of consistency when there is none.
Post a Comment