问题描述
为什么在 JVM 内部类中存在的某些代码模式被转换为内部函数,而从我自己的类中调用的相同模式却不是.
Why certain code patterns when present within JVM internal classes are turned into an intrinsic function, whereas the same patterns when called from my own class are not.
例子:
bitCount 函数,当从 Integer.bitCount(i) 中调用时,将变成一个内在函数.但是,当复制到我的班级然后被调用时,将需要更长的时间来执行.
bitCount function, when called from within Integer.bitCount(i) will be turned into an intrinsic. But when copied into my class and then called will take much longer to execute.
比较
Integer.bitCount(i)
MyClass.bitCount(i)
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
推荐答案
答案很简单:这样定义一个内部函数是因为存在一种更快、更原生的方法来获取函数的结果,并且它适用于万一感谢指定的映射.
The answer is simple: an intrinsic function is defined in this way because a faster, native way to obtain the result of the function exists and it is applied in case thanks to a specified mapping.
这根本与编译无关.Integer.bitCount
的特殊之处在于实现被标记为可替换为原生 asm 指令 POPCNT.基本上,在使用 Integer.bitCount
函数(如果 CPU 支持该指令)时会使用此本机指令,当您声明自己的函数副本时,将使用正常实现.
That's not something related to compilation at all. Integer.bitCount
is special in the sense that implementation is marked to be replaceable with a native asm instruction POPCNT. Basically this native instruction is used when using the Integer.bitCount
function (if the CPU supports that instruction), when you declare your own copy of the function the normal implementation is used.
为什么JVM能够识别出可以优化的功能?因为它是硬编码的 某处 在JDK中,与代码相似度无关.
Why JVM is able to recognize that the function can be optimized? Because it's hardcoded somewhere in the JDK, that has nothing to do with similarity to the code.
这篇关于JVM 什么时候使用内部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!