gpt4 book ai didi

jvm - 使用 invokespecial 调用公共(public)方法?

转载 作者:行者123 更新时间:2023-12-02 14:47:19 25 4
gpt4 key购买 nike

任何能回答这个问题的人都知道,JVM 支持几种用于调用方法的字节码指令(invokevirtualinvokespecialinvokestatic , ...)

大多数对实例方法的方法调用都是通过 invokevirtual 进行的,但是私有(private)方法和初始化方法是通过 invokespecial 调用的,如 JVM 规范中所述:

The difference between the invokespecial and the invokevirtual instructions is that invokevirtual invokes a method based on the class of the object. The invokespecial instruction is used to invoke instance initialization methods as well as private methods and methods of a superclass of the current class.

据我了解,invokevirtual 执行 vtable 查找以解析方法,而 invokespecial 由于在链接时已知正确的方法实现,因此静态解析。

我的问题是,在方法所有者的具体类在编译时已知的情况下,为什么 invokespecial 不用于调用 public 方法?在我看来,出于效率原因,避免 vtable 查找是可取的。但显然我对 JVM 有一些不了解的地方。

最佳答案

首先,在编译时知道特定的调用目标并不容易。 JVM 可以动态加载新的类,甚至可以在运行时重新定义现有的类。在编译时显示为非虚拟的公共(public)方法可能在运行时恰好变为虚拟。

您说得对,vtable 查找会对性能产生影响。但是,invokevirtual 字节码根本不暗示 vtable 查找。

例如,HotSpot JVM 尽其所能去虚拟化方法调用。它依靠类层次结构分析和运行时类型配置文件将 invokevirtual 转换为直接调用,或者更好的是,将“虚拟”方法直接内联到调用站点。只有真正的巨态调用站点(在运行时具有 3 个或更多目标)才会进行 vtable 查找。

也就是说,对于现代 JVM,当目标方法实际上是非虚拟的时,invokespecialinvokevirtual 之间没有性能差异。

关于jvm - 使用 invokespecial 调用公共(public)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58237483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com