Performance, Java Generics

Does Generics give Java an edge over collections?

For example, in C # there is a performance advantage, since it helps to avoid boxing / unpacking, but, as I understand it, in Java there is no β€œidea” of generics at the level of byte code, so after compilation it has the same byte code as for collections.

How to say that there is no performance advantage?

+6
source share
6 answers

I think this link can be very useful.

Comparing Java and C # Generics

As you said in C # performance, you win because Generics helps you avoid boxing / unboxing. By and large, the reason is that generic .NET files support value types, but Java generics do not work with primitive types, and therefore they cannot remove the overhead of boxing / unpacking.

But still you have a check on the type of compilation time and the lack of an explicit cast to your code.

+6
source

How to say that there is no performance advantage?

It is not as clear as this, but in general you are right. In Java, generators are just a good way for the compiler to do all the casting for you in the background.

However, the compiler can still use better casting approaches than you could implement passing Object everywhere.

+3
source

You correctly say:

in Java there is no β€œidea” of generics at the level of byte code

Thus, in Generics in Java there is no performance increase.

+2
source

Lack of performance, just programmable by type of programming :)

+1
source

Generics imposes type checking compile-time checks, but writes bytecode that works with objects. That way, List is a List<String> when the code runs, but you are not allowed to use list.add(new Date(...)) because the compiler will refuse your neglect of a generic type.

As a result of running a list as a list under covers, Generics does not have any performance benefit or performance penalty over unrelated common data structures.

+1
source

Java generators have very little effect on performance, as they are a function of checking the static type, and not (a lot) are present at runtime. They add a few castings that you may have abandoned the non-universal version.

However, using the compile-time function also means that redundant information is not stored at run time. Additional accounting will have some negative effects.

+1
source

Source: https://habr.com/ru/post/888343/


All Articles