五種URL參數解析方法的性能比較

由於在最近項目中須要解析日誌中的 URL 的參數,因此我對比了一下五種不一樣 的 URL 參數解析方法的性能。 URL 參數解析方法: httpclient org.apache.http.client.utils.URLEncodedUtils URLEncodedUtils.parse(query, Charset.forName("UTF-8")); jettyUtil org.eclipse.jetty.util.UrlEncoded MultiMap values = new MultiMap();   UrlEncoded.decodeTo(query, values, "UTF-8", 1000); tomcat org.apache.catalina.util.RequestUtil Map values = new HashMap();   RequestUtil.parseParameters(values, query, "UTF-8"); regex 正則表達式 String u = URLDecoder.decode(url, "UTF-8");   for (String s : parameters) {       Pattern p = Pattern.compile(s + "=([^&]*)(&|$)");       Matcher m = p.matcher(u);       if (m.find()) {           m.group(1);       }   } split 使用String 的split 方法對 URL 進行分割,而後用equals 匹配對應的 參數 String u = URLDecoder.decode(url, "UTF-8");   for (String s : parameters) {       String[] a = new String[100];       if (u.indexOf(s) != -1) {           a = (u.substring(u.indexOf(s))).split("&");           a[0].split("=");       }   }   前三者是 httpclient, jetty, tomcat 使用的 URL 解析工具。Split 方法是最簡單 也是最直觀的解析方法,regex 則使用了正則表達式去匹配參數。 性能比較 用這五種方法分別解析同一個URL 100000遍,獲得以下的數據。考慮到 Java 的代 碼緩存特性,共運行4遍這樣的測試,測試數據取最後一次的結果。 ---first--- httpclient: 3063 jettyUtil: 1767 tomcat: 2405 regex: 9226 split: 22905 ---second--- httpclient: 2766 jettyUtil: 1618 tomcat: 2229 regex: 9025 split: 23661 ---third--- httpclient: 2799 jettyUtil: 1632 tomcat: 2251 regex: 8761 split: 23476 ---fouth--- httpclient: 2989 jettyUtil: 1634 tomcat: 2251 regex: 8895 split: 23571 在最後一組數據中,咱們能夠看到 jettyUtil 的性能最高,split 和 regex 的方法性 能較差。 總結 jettyUtil 解析URL的性能在五種中最高,若是咱們在項目中須要解析 URL ,應該 儘量的考慮使用 jettyUtil 來解析。 參考連接 本測試的代碼 https://gist.github.com/hellojinjie/5651936 Tomcat RequestUtil 的代碼http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/util/RequestUtil.java?view=markup jettyUtil UrlEncoded 的代碼 http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java httpclient URLEncodedUtils 的代碼 https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-beta1/module-client/src/main/java/org/apache/http/client/utils/URLEncodedUtils.java 來源:Heck's Blog 地址:http://www.hecks.tk/post/433/ 轉載時須以連接形式註明做者和原始出處及本聲明,不然將追究法律責任,謝謝配合!
相關文章
相關標籤/搜索