为什么在JVM内部类中存在的某些代码模式被转换为内部函数,而从我自己的类调用时相同的模式则不然.
例:
bitCount函数,当从Integer.bitCount(i)内调用时,将变成一个内在函数.但是当复制到我的类中然后调用将需要更长的时间来执行.
相比
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;
}
Run Code Online (Sandbox Code Playgroud) 在我的工作中,所有开发人员都使用Double.valueOf而不是new Double构造函数。在每种情况下。对于 Integer 或 Short 我可以理解它的缓存值但不是 fordouble和float。
我在 OpenJDK 源代码中查看 Double.valueOf :
/**
* Returns a {@code Double} instance representing the specified
* {@code double} value.
* If a new {@code Double} instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Double(double)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested …Run Code Online (Sandbox Code Playgroud) 原始代码是:
public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
return 32;
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i …Run Code Online (Sandbox Code Playgroud)