一直听说java反射性能不太好,今天就好奇简单测试一下。下面是测试代码:
package com.koma.mode.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Create by koma on 2017/12/20
*/
public class Test {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
long num = 0;
// new一个Student对象
Student student = new Student();
long before = System.currentTimeMillis();
for (long i = 0; i < 10000000; i++) {
student.setAge(i);
num += student.getAge();
}
long after = System.currentTimeMillis() - before;
System.out.println("new时间:" + after+" 总数:"+num);
// 得到Student的class对象
Class<?> aClass = Class.forName("com.koma.mode.test.Student");
Object o = aClass.newInstance();
Method setAge = aClass.getMethod("setAge", Long.class);
Method getAge = aClass.getMethod("getAge");
long count = 0;
before=System.currentTimeMillis();
for (long i = 0; i < 10000000; i++) {
setAge.invoke(o, i);
Long tmp = (Long) getAge.invoke(o);
count += tmp;
}
after=System.currentTimeMillis()-before;
System.out.println("class时间:"+after+" 总数:"+count);
}
}
结果如下:
new时间:96 总数:49999995000000
class时间:185 总数:49999995000000
总结:我用的jdk版本是1.8.0_91,发现用反射性能也还好,不是太低,随着jdk版本越来越高,反射的性能也优化的越来越好。印象当中性能不好,可能还停留在jdk6以前。