反射性能测试
下面我们测试了循环调用十亿次类里面的方法
- 正常先实例化后用对象调用,这样最快
- 同时也可以用反射调用方法,这样是最慢的要比直接正常调用快三百倍左右
- 如果不进行访问权限的话,可以比反射调用快三倍
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Time;
public class Test01 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
System.out.println(Runtime.getRuntime().availableProcessors());
long bg=System.currentTimeMillis();
So so=new So();
for (int i = 0; i < 1000000000; i++) {
so.getId();
}
long go=System.currentTimeMillis();
System.out.println((go-bg)+"ms");
System.out.println("==========================");
long bg1=System.currentTimeMillis();
Class c1=so.getClass();
Method method= c1.getDeclaredMethod("getId",null);
for (int i = 0; i < 1000000000; i++) {
method.invoke(so,null);
}
long go1=System.currentTimeMillis();
System.out.println((go1-bg1)+"ms");
System.out.println("--------------------------------");
long bg2=System.currentTimeMillis();
method.setAccessible(true);
for (int i = 0; i < 1000000000; i++) {
method.invoke(so,null);
}
long go2=System.currentTimeMillis();
System.out.println((go2-bg2)+"ms");
}
}
class So{
private int id;
public int getId() {
return id;
}
}
运算结果:
12
5ms
==========================
2896ms
--------------------------------
1032ms
Process finished with exit code 0