Java 类反射性能测试及对架构工作的一些思考
Java 类反射性能测试及对架构工作的一些思考
通过对比静态调用与类反射调用方法的效率,来了解现代框架中大量应用的反射调用对性能的影响程度。以便在系统架构中对性能与开发便利性之间进行权衡与取舍。
代码1:
/** * */package test;import java.lang.reflect.Method;/** * @author jetlong * */public class PerformanceTest { /** * @param args */ public static void main(String[] args) throws Exception { int testTime = 10000000; PerformanceTest test = new PerformanceTest(); String msg = "this is test message"; long bTime = System.currentTimeMillis(); for(int i=0; i<testTime; i++) { test.takeAction(msg); } long eTime = System.currentTimeMillis(); System.out.println(eTime - bTime); bTime = System.currentTimeMillis(); for(int i=0; i<testTime; i++) { Method method = test.getClass().getMethod("takeAction", String.class); method.invoke(test, msg); } eTime = System.currentTimeMillis(); System.out.println(eTime - bTime); } public int takeAction(String msg) { return (msg.length() * (int)(System.currentTimeMillis() % 100000)); }}