将Users类的getName方法分别用以下三种方式
- 普通方式反射方式反射方式关闭安全检测
调用1000000000次,记录所用时间,分析三种方式的性能。
//分析性能问题
public class Test {
//普通方式调用
public static void test1(){
Users user = new Users();
long startTime = System.currentTimeMillis();
for (int i = 0; i<1000000000; i++){
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方式:" + (endTime-startTime) + "ms");
}
//反射方式调用
public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Users user = new Users();
Class c = user.getClass();
Method getName = c.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");
}
//反射方式调用,关闭安全检测
public static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Users user = new Users();
Class c = user.getClass();
Method getName = c.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");
}
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
test1();
test2();
test3();
}
}
普通方式:3ms
反射方式:3348ms
反射方式,关闭安全检测:1506ms
结论
普通方式调用方法的性能远高于反射调用。
应用反射方式时,若某方法调用频繁,可关闭安全检测(setAccessible(true)),可提升约一倍的性能。



