JIT 可以从泛型中受益吗?
众所周知,泛型类型无法在编译过程中幸存下来。他们被班级演员取代。
但尽管如此,类型信息存在于类文件中,并且可以使用反射查看:
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();
}
}
执行时,这将打印 java.lang.String
。
JIT 可以使用它进行某种优化吗?或者从 JIT 的角度来看这些信息毫无用处?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以,但据我所知不行。为了解决这个问题,Scala 最近在编译时添加了一些支持 类型专门化,它生成类的专门版本 - 没有任何强制转换 - 并将它们透明地放置到代码库的其余部分,以便代码仍然按预期工作。在这些情况下,编译后的 Scala 代码实际上比 Java 快得多,因为带有泛型的 Java 将始终使用强制转换。
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.
JVM 不可能避免转换对象,因为底层集合可能没有字符串。例如,如果使用擦除来将整数添加到列表中。
我想不出潜在的优化,而且还有很多潜在的优化是 JIT 无法做到的。 ;)
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. ;)