package com.dasenlin.reflectionconstractor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 对比反射机制下程序运行的效率
* @author Administrator
*
*/
public class Effectiveness {
/**
* 正常调动
*/
public static void test01(){
User u = new User();
long startTime = System.currentTimeMillis();
for(int i=0;i<1000000000L;i++){
u.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方法调用执行10亿次,耗时"+(endTime-startTime));
}
/**
* 有安全监测机制的调用
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
@SuppressWarnings("all")
public static void test02() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
User u = new User();
Class clazz = u.getClass();
Method m =clazz.getDeclaredMethod("getName",null);
long startTime = System.currentTimeMillis();
for(int i=0;i<1000000000L;i++){
m.invoke(u, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射机制调用执行10亿次,耗时"+(endTime-startTime));
}
/**
* 跳过安全检查的调用
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
@SuppressWarnings("all")
public static void test03() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
User u =new User();
Class calzz =u.getClass();
Method m =calzz.getDeclaredMethod("getName", null);
m.setAccessible(true);
long startTime = System.currentTimeMillis();
for(int i=0;i<1000000000L;i++){
m.invoke(u, null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射机制跳过安全检查调用执行10亿次,耗时"+(endTime-startTime));
}
/**
* 测试方法调用
* @param args
* 本机测试:普通方法调用执行10亿次,耗时1777ms
* 反射机制调用执行10亿次,耗时47946ms
* 反射机制跳过安全检查调用执行10亿次,耗时10482ms
*/
public static void main(String[] args) {
test01();
try {
test02();
test03();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
java反射机制的性能问题,对比测试!
最新推荐文章于 2022-11-25 11:21:49 发布