gpt4 book ai didi

java - 为什么任何标记为 final 的类都不允许编译器去虚拟化方法调用

转载 作者:行者123 更新时间:2023-11-29 05:05:10 24 4
gpt4 key购买 nike

this article , 我惊讶地读到:

I always imagined that having a final method meant that the compiler would compile all calls to it using invokespecial instead of invokevirtual, to "devirtualize" the method calls since it already knows for sure at compile-time where to transfer execution. Doing this at compile time seems like a trivial optimization, while leaving this up to the JIT is far more complex. But no, the compiler doesn't do this. It's not even legal to do it!

在编译时执行此操作似乎是一个微不足道的优化,因为它在编译时已经确定将执行转移到何处。这没有发生的原因是什么?

最佳答案

发布 the answer that EJP pointed out in the comments :

Java has a separate compilation model, thus it forbids cross-file optimization (with a notable exception, compile-time constant inlining). What if you change the method to non-final, and do not recompile the clients? What if you do runtime bytecode replacement (search for "instrumentation")?

Side note: as an engineer, your expectations should be a function of the tool. This is not C++. Where you can afford an interpreter, bytecode optimization is premature optimization.

Keep your mind object-oriented. You ask the compiler to do it, let it decide the best behind the scenes; if a 20yo compiler does not do it, it's probably unimportant. -O is well documented (at least on Oracle's JDK) and it just inlines the private and static methods inside the file that declares them.

关于java - 为什么任何标记为 final 的类都不允许编译器去虚拟化方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604230/

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