Performance difference in Java generic types vs oldstyle generics?
I am wondering if there is any differenc开发者_开发知识库e in runtime between a generic container implemented using the language features for generics, introduced Java 1.5, compared to doing it with just inheritance and explicit typecasts. And if there is, which would give the highest performance.
To be specific, lets say I have a base class and a subclass:
public class Base { }
public class Sub extends Base { }
And I define a container type in terms of the base class. Then what I am interested in is what happens when a container instance is known to contain a certain subclass. Before 1.5 I would have no choice but to implement the container like this (never mind that it is too simplified to make actual sense):
public class OldstyleContainer {
private Base x;
public void set(Base x) { this.x = x; }
public Base get() { return x; }
}
And a use of the class where the specific type of the known element is known could look like this:
public Sub oldstylePut(OldstyleContainer c, Sub s) {
Sub t = (Sub) c.get();
c.set(s);
return t;
}
Now, with the language features for generics, I would instead define the container like this:
public class GenericsContainer<T extends Base> {
private T x;
public void set(T x) { this.x = x; }
public T get() { return x; }
}
And the corresponding use would be like this:
public Sub genericsPut(GenericsContainer<Sub> c, Sub s) {
Sub t = c.get();
c.set(s);
return t;
}
The generic version code looks (very) slightly simpler, because there is no need for an explicit cast. But my question is, is there any real difference in runtime, or does that cast still exist in the byte code? Is there any other difference?
Generics are erased - so by the time the code runs the compiler has put the casts in anyway. You just don't have to do them yourself in the source code when using Generics. So don't consider performance - use Generics to make code safer.
No Generic information isn't available at runtime, its only compile time feature.
Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler.
精彩评论