不解释,直接上代码。
/**
*
*/
package reflect;
import java.io.Serializable;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
/**
* @author duchao
*
*/
public class TestUnsafe {
/**
* @param args
*/
public static void main(String[] args) {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
TestBean testBean = new TestBean();
Field intField = TestBean.class.getDeclaredField("age");
long start = 0, stop = 0;
start = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
intField.get(testBean);
}
stop = System.currentTimeMillis();
System.out.println("使用Field.get方式时间:" + (stop - start));
start = System.currentTimeMillis();
long offset = unsafe.objectFieldOffset(intField);
for (int i = 0; i < 100000000; i++) {
unsafe.getInt(testBean, offset);
}
stop = System.currentTimeMillis();
System.out.println("使用Unsafe.get方式时间:" + (stop - start));
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @author haitao.yao Dec 14, 2010
*/
static class TestBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5994966479456252766L;
private String name;
public int age;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
}
分别对Field.get方式和Unsafe.getInt方式进行统计,各进行一亿次操作:
使用Field.get方式时间:48843
使用Unsafe.get方式时间:63
单位是毫秒。。