Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a JIT take a benefit from Generics?

It is well known, that generic types don't survive the compiling process. They are replaced by class casts.

But nevertheless, the type information is present in the class file and can be seen 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 executed, this will print java.lang.String.

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

like image 238
yankee Avatar asked Jul 27 '11 09:07

yankee


2 Answers

It could, but as far as I know it doesn't. To work around this, Scala added support somewhat recently to compile-time type specialization of generic code which generates specialized versions of the class - without any casts - and places them to the rest of the codebase transparently so that the code still works as expected. In these cases, compiled Scala code can actually be noticeably faster than Java since Java with Generics will always use casts.

like image 112
Esko Avatar answered Sep 21 '22 14:09

Esko


Its not possible for the JVM to avoid casting the object as the underlying collection may not have Strings. e.g. if erasure is used to add an Integer to the list.

I can't think of a potential optimisation and there are plenty of potential optimisation the JIT doesn't do. ;)

like image 38
Peter Lawrey Avatar answered Sep 18 '22 14:09

Peter Lawrey