網頁

2013年6月6日 星期四

[java] Performance of StringTokenizer V.S. String.split

java 用來分割字串的方法,就我所知道有StringTokenizer和String.split。為了知道哪種效能比較好,寫了個小程式測了一下。
import java.lang.StringBuilder; import java.lang.System; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class Test { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i=1000; i<1100; i++) { sb.append(i).append(" "); } String str = sb.toString(); int runs = 100000; for (int i = 0; i < 5; i++) { { long start = System.nanoTime(); for (int r = 0; r < runs; r++) { StringTokenizer st = new StringTokenizer(str); List list = new ArrayList(); while (st.hasMoreTokens()) { list.add(st.nextToken()); } } long time = System.nanoTime() - start; System.out.printf("StringTokenizer took an average of %.1f us%n", time / runs / 1000.0); } { long start = System.nanoTime(); for (int r = 0; r < runs; r++) { List list = Arrays.asList(str.split(" ")); } long time = System.nanoTime() - start; System.out.printf("String.split took an average of %.1f us%n", time / runs / 1000.0); } } } }
結果顯示:
StringTokenizer took an average of 12.7 us String.split took an average of 9.8 us StringTokenizer took an average of 12.6 us String.split took an average of 9.4 us StringTokenizer took an average of 12.6 us String.split took an average of 9.4 us StringTokenizer took an average of 13.2 us String.split took an average of 9.4 us StringTokenizer took an average of 12.5 us String.split took an average of 9.5 us
看來String.split表現得比較好

沒有留言:

張貼留言