通过代码的方式来检验三种方式调用的效率
//分析性能问题
public class Test10 {
//普通方式调用
public static void test01(){
User user1 = new User();
long startTime =System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
user1.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通执行10亿次:"+ (endTime-startTime) +"ms");
}
//反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user1 = new User();
Class c1 = user1.getClass();
Method getName = c1.getMethod("getName");
long startTime =System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user1);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式执行10亿次:"+ (endTime-startTime) +"ms");
}
//反射方式调用,关闭检测
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user1 = new User();
Class c1 = user1.getClass();
Method getName = c1.getMethod("getName");
getName.setAccessible(true);
long startTime =System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user1);
}
long endTime = System.currentTimeMillis();
System.out.println("关闭检测执行10亿次:"+ (endTime-startTime) +"ms");
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
如图所示,三个方法分别用普通方法、反射和关闭检测的放射来调用10亿次getName的方法,通过时间差来反应其效率。
运行结果:
由此可见,普通执行的性能>关闭检测反射执行的性能>反射执行的性能
笔记根据b站狂神说视频:https://www.bilibili.com/video/BV1p4411P7V3?p=14