package com.yiheng.yiheng_04_CreatObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//测试普通、反射、关闭安全检测的反射三种方式调用10亿次方法的速度差距
public class Test02 {
public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
test01();
test02();
test03();
}
//普通调用
static void test01(){
User user = new User();
long startTime = System.currentTimeMillis();//得到开始时间,毫秒计
for (int i = 0; i < 1000000000; i++) {
user.getName();//10次调用该方法
}
long endTime = System.currentTimeMillis();//得到结束时间,毫秒计
System.out.println("普通调用:"+(endTime-startTime)+"ms");
}
//通过反射调用
static void test02() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Class<User> userClass = User.class;
User user = userClass.newInstance();
Method getName = userClass.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();//得到开始时间,毫秒计
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();//得到结束时间,毫秒计
System.out.println("反射调用:"+(endTime-startTime)+"ms");
}
//关闭安全检测,反射调用
static void test03() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Class<User> userClass = User.class;
User user = userClass.newInstance();
Method getName = userClass.getDeclaredMethod("getName", null);
getName.setAccessible(true);//关闭安全检测
long startTime = System.currentTimeMillis();//得到开始时间,毫秒计
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();//得到结束时间,毫秒计
System.out.println("关闭安全检测反射调用:"+(endTime-startTime)+"ms");
}
}
结论:
反射调用是用了invoke()方法。
1、直接调用最快
2、其次是关闭安全检测的反射调用
3、再次是反射调用