测试可能有缺陷。
generallythoughthejvmmayoptimizethenormalinstantiationbutcouldnotmakeoptimizationsforthereflectiveusecase。
关于什么时候想知道,我们添加了预热阶段,并使用了数组来保持创建的对象。 这类似于实际程序可能做的事情。 我在OSX,jdk7系统上运行测试代码,得到了这个:
reflectinginstantiationtook :5180 ms
正规教育中心:2001 ms
测试更改:
公共类测试{
静态类b {
() ) ) ) )。
publicstaticlongtimediff { longold }
return System.nanoTime ()- old;
() ) ) ) )。
publicstaticvoidmain (string args [ ] ) throws Exception {
int numTrials=10000000;
B[] bees=new B[numTrials];
Class c=B.class;
for(intI=0; i numTrials; I ) {
bees[i]=c.newInstance (;
() ) ) ) )。
for(intI=0; i numTrials; I ) {
bees[i]=new B (;
() ) ) ) )。
long nanos;
nanos=System.nanoTime (;
for(intI=0; i numTrials; I ) {
bees[i]=c.newInstance (;
() ) ) ) )。
system.out.println (reflectinginstantiationtook : (time unit.nanoseconds.tomillis ) timediff (nanos ) ) ms ) )
nanos=System.nanoTime (;
for(intI=0; i numTrials; I ) {
bees[i]=new B (;
() ) ) ) )。
system.out.println (' normalinstaniationtook : ' time unit.nanoseconds.tomillis (timediff ) nanos ) ) (ms );
() ) ) ) )。
() ) ) ) )。