package Reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
普通方法执行10亿次时间2ms
反射方法执行10亿次时间2660ms
关闭安全检测执行10亿次时间1634ms
*/
//分析性能问题
public class Demo04 {
public static void test01(){
long startTime = System.currentTimeMillis();
for (int i = 0; i <10_0000_0000 ; i++) {
User.test();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方法执行10亿次时间"+(endTime-startTime)+"ms");
}
public static void test02() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
long startTime = System.currentTimeMillis();
User user = new User();
Class c = user.getClass();
Method method = c.getMethod("test",null);
for (int i = 0; i <10_0000_0000 ; i++) {
method.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方法执行10亿次时间"+(endTime-startTime)+"ms");
}
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
long startTime = System.currentTimeMillis();
User user = new User();
Class c = user.getClass();
Method method = c.getMethod("test",null);
method.setAccessible(true);
for (int i = 0; i <10_0000_0000 ; i++) {
method.invoke(user, null);
}
long endTime = System.currentTimeMillis();
System.out.println("关闭安全检测执行10亿次时间"+(endTime-startTime)+"ms");
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
test01();
test02();
test03();
}
}
class User{
private String name;
int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public static void say(String str){
System.out.println(str);
}
public static void test(){
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
简单测试普通方法 反射方法 关闭安全监测反射 调用 类的方法速度
最新推荐文章于 2023-08-25 18:34:12 发布