朋友問個人問題,網上搜了下,都說StringTokenizer性能要好些,不過也有反對意見,仍是本身試驗下。 html
一百萬以空格區分的字符串,拆分後從新組成不帶空格的串。 java
import java.util.Random; import java.util.StringTokenizer; /** * * @author Jason Li 2014-6-3 * StringTokenizer和Spilt速度比較 * */ public class StringTest { public static void main(String[] args) { String str = buildString(1_000_000); //1.7新特性, 1000000 long start; long end; System.out.println("-----------StringTokenizer start-----------"); start = System.currentTimeMillis(); StringTokenizer st = new StringTokenizer(str); StringBuilder sb = new StringBuilder(); while(st.hasMoreTokens()){ sb.append(st.nextToken()); } end = System.currentTimeMillis(); System.out.println("StringTokenizer time use:" + (end-start)); System.out.println("-----------StringSpilt start-----------"); start = System.currentTimeMillis(); StringBuilder sb2 = new StringBuilder(); String[] strs = str.split("\\s"); for(String s: strs){ sb2.append(s); } end = System.currentTimeMillis(); System.out.println("StringSpilt time use:" + (end-start)); } //創建一個長字符串, //其中有空格,以便拆分紅length長度的n個字符串 private static String buildString(int length) { StringBuilder sb = new StringBuilder(); Random r =new Random(); for (int i = 0; i <length;i++ ){ for (int j = r.nextInt(10); j>0 ;j--){ sb.append((char)('a' + r.nextInt(26))); } sb.append(" "); } return sb.toString(); } }
-----------StringTokenizer start----------- StringTokenizer time use:131 -----------StringSpilt start----------- StringSpilt time use:509
StringTokenizer確實更快些,至於爲何jdk裏不推薦使用了,還要再研究。 app