JIT 可以从泛型中受益吗?

发布于 2024-11-27 01:30:41 字数 620 浏览 1 评论 0原文

众所周知,泛型类型无法在编译过程中幸存下来。他们被班级演员取代。

但尽管如此,类型信息存在于类文件中,并且可以使用反射查看:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪我闹别瞎闹 2024-12-04 01:30:41

可以,但据我所知不行。为了解决这个问题,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.

孤单情人 2024-12-04 01:30:41

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. ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文