编辑:maaartinus给出了我正在寻找的答案,而tmyklebu关于这个问题的数据帮助了很多,所以谢谢两者!:)
我已经阅读了一些关于HotSpot如何在代码中注入一些"内在函数"的内容,特别是对于Java标准Math libs(来自这里)
所以我决定尝试一下,看看HotSpot可以直接做出多大的反对(特别是因为我听说min/max可以编译成无分支的asm).
public static final int max ( final int a, final int b )
{
if ( a > b )
{
return a;
}
return b;
}
Run Code Online (Sandbox Code Playgroud)
这是我的实施.从另一个SO问题我已经读过,使用三元运算符使用额外的寄存器,我没有发现在执行if块和使用三元运算符之间存在显着差异(即返回(a> b)?a:b).
分配一个8Mb的int数组(即200万个值)并随机化它,我做了以下测试:
try ( final Benchmark bench = new Benchmark( "millis to max" ) )
{
int max = Integer.MIN_VALUE;
for ( int i = 0; i < array.length; ++i )
{
max = OpsMath.max( max, array[i] );
// max = Math.max( max, array[i] );
} …Run Code Online (Sandbox Code Playgroud) 我的疑问是这个:
在Java中,不允许从数组继承,即,不能执行以下操作:
class FloatVec extends float[]
{
// Vector methods.
}
FloatVec somevec = new FloatVec()[] { 1, 2, 3 }; // With array initializer.
Run Code Online (Sandbox Code Playgroud)
甚至更好:
class FloatVec3 extends float[3]
{
// Regular accessor.
public float getX() {
return this[0];
}
// Or say, make it the 'this' implicit like with other fields:
public void setVec(float x, float y, float z) {
[0] = x;
[1] = y;
[2] = z;
}
// And specific vec3 methods like:
public float …Run Code Online (Sandbox Code Playgroud) 我的问题如下:
通常用于Java代码的通用集合实现如下:
public class GenericCollection<T> {
private Object[] data;
public GenericCollection () {
// Backing array is a plain object array.
this.data = new Object[10];
}
@SuppressWarnings( "unchecked" )
public T get(int index) {
// And we just cast to appropriate type when needed.
return (T) this.data[index];
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用例如:
for (MyObject obj : genericCollection) {
obj.myObjectMethod();
}
Run Code Online (Sandbox Code Playgroud)
由于擦除了genericCollection的泛型类型,JVM似乎没有办法知道在genericCollection的'data'数组中真正只有MyObject实例,因为数组的实际类型是Object,可能有一个其中的字符串,并在其上调用'myObjectMethod'将引发异常.
所以我假设JVM必须做一些运行时检查体操才能知道GenericCollection实例中究竟是什么.
现在看看这个实现:
public class GenericCollection<T> {
private T[] data;
@SuppressWarnings( "unchecked" )
public GenericCollection ( Class<T> type ) {
// Create …Run Code Online (Sandbox Code Playgroud) java ×3
jvm ×2
jvm-hotspot ×2
arrays ×1
generics ×1
inheritance ×1
math ×1
max ×1
min ×1
optimization ×1
performance ×1