一直聽別人說java 的反射機制很慢,儘可能別用。以後筆者進入一個新的公司,熟悉系統的時候,發現系統的核心跳轉實現用的是asm代理,而不是使用反射(反射的實現更簡單),當時筆者就問了下做者,做者說是爲了提升性能。當時我就心想,反射到底慢到了什麼程度,弄的人談虎色變,因而筆者就作了一個測試,測試下反射,看到底慢到了什麼程度。 java
測試代碼以下: 數據庫
package com.sohu.smc.yueExam; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.TimeZone; /** * 測試反射的性能 * @author shaojieyue * */ public class TeflectPerformanceTest { private long count;//循環執行的次數 public void exec() throws Exception{ long end = 0L; long start=0L; String str="abcde"; Method method=null; String methodName="replace"; String[] args={"abc","abc"}; method= String.class.getDeclaredMethod(methodName, CharSequence.class,CharSequence.class); start=System.currentTimeMillis(); for(long i=0;i<count;i++){ method.invoke(str,args); } end=System.currentTimeMillis(); System.out.println("--->反射執行時間(有緩存Method): "+date(end-start)); start=System.currentTimeMillis(); for(long i=0;i<count;i++){ invokeNoCache(methodName,str,args); } end=System.currentTimeMillis(); System.out.println("--->反射執行時間(無緩存): "+date(end-start)); start=System.currentTimeMillis(); for(long i=0;i<count;i++){ str.replace("abc","abc" ); } end=System.currentTimeMillis(); System.out.println("--->傳統執行時間: "+date(end-start)); } private String date(long millis){ SimpleDateFormat formatter = new SimpleDateFormat("HH小時mm分鐘ss秒"); formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00")); String hms = formatter.format(millis); return hms; } /** * 非緩存的方式調用 * @param methodName * @param target * @param args * @throws Exception */ private void invokeNoCache(String methodName,String target,String[] args) throws Exception{ Method method= String.class.getDeclaredMethod("replace", CharSequence.class,CharSequence.class); method.invoke(target,args); } public static void main(String[] args) throws Exception { long count=Long.valueOf(args[0]); TeflectPerformanceTest tpt = new TeflectPerformanceTest(); tpt.count=count; tpt.exec(); } }
測試參數:300000000 三千萬次 緩存
測試結果: 框架
--->反射執行時間(有緩存Method): 00小時01分鐘42秒
--->反射執行時間(無緩存): 00小時03分鐘25秒
--->傳統執行時間: 00小時01分鐘41秒
性能
PS:有人說,系統框架對系統性能的影響是很微弱的,大部分性能的瓶頸都是在系統業務自己,和數據庫方面。 測試
筆者感受有必定的道理(不是任什麼時候候都對,實際狀況實際出發),不知道各位怎麼看? spa