开发者

Performance, Java Generics

Does Generics in Java give any performans advantage over collections.

For example in C# there is a performance advantage as it helps to avoid boxing/unboxing, but as I understand in Java there is no "idea" of generics at byte code level, so after comp开发者_开发知识库ilation it has the same byte code as for collections.

So is it right to say that there is no performance advantage?


I think this link can be very helpful .

Comparing Java and C# Generics

As you have said in C# performance will benefit as Generics helps you to avoid boxing/unboxing. In depth the reason is that .NET generics support value types but Java generics don't work with the primitive types and that is why it can't remove the overhead of boxing/unboxing.

But still you have compile time type checking and no need of explicit casts in your code.


So is it right to say that there is no performance advantage?

It's not as clear cut as that, but in general, you are correct. In Java, generics are simply a nice way for the compiler to do all of the casting for you in the background.

Still, the compiler may still end up using better approaches to casting than you might implement yourself passing Object around everywhere.


You are correct in saying:

in Java there is no "idea" of generics at byte code level

So, there is no performance gain from Generics in Java.


No performance advantage, just type-safe programming :)


Generics imposes compile time verification of type checking, but writes bytecode that operates on Objects. So a List is a List<String> when the code runs, but you are not allowed to list.add(new Date(...)) to it because the compiler will balk at your disregard for the genericsized type.

As a result of running List as List under the covers, Generics has absolutely no performance benefit or detriment at runtime when compared to unbound generic understanding data structures.


Java generics make very little difference to performance, as they are a static type checking feature and not (much) present at runtime. They do add a few casts that you may have elided in the non-generic version.

However, being a compile-time feature also means that they superfluous information is not kept at runtime. The extra accounting would have some negative performance effects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜