Can JIT take advantage of Generics?

It is well known that generic types do not withstand the compilation process. They are replaced by classes.

But, nevertheless, type information is present in the class file and can be visible using reflection:

public class Demo { private List<String> list; public Demo() throws SecurityException, NoSuchFieldException { System.out.println(((Class<?>)((ParameterizedType) getClass().getDeclaredField("list").getGenericType()).getActualTypeArguments()[0]).getName()); } public static void main(String[] args) throws SecurityException, NoSuchFieldException { new Demo(); } } 

When doing this, java.lang.String will be printed.

Can JIT use this for some kind of optimization? Or is this information from a JIT point of view useless?

+8
java optimization jit
source share
2 answers

It could, but as far as I know, it is not. To get around this, Scala recently added support for compiling a specialization type of generic code that generates specialized versions of the class β€” without any casts β€” and puts them in the rest of the code transparently so that the code will still work as expected. In these cases, the compiled Scala code can be noticeably faster than Java, since Java with Generics will always use casts.

+3
source share

It is not possible for the JVM to avoid throwing an object, since the underlying collection may not have rows. for example, if erasure is used to add integers to a list.

I can’t think of potential optimization and there is a lot of potential optimization that JIT does not do;)

+2
source share

All Articles