日期:2014-05-16 浏览次数:20939 次
// Apache StringUtils... String[] tokens1= StringUtils.split("one,two,three",','); // Google Guava splitter... Iteratable<String> tokens2 = Splitter.on(','),split("one,two,three");
Splitter niceCommaSplitter = Splitter.on(',') .omitEmptyString().trimResults(); niceCommaSplitter.split("one,, two, three"); //"one","two","three" niceCommaSplitter.split(" four , five "); //"four","five"
final String numberList = "One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten"; long start = System.currentTimeMillis(); for(int i=0; i<1000000; i++) { StringUtils.split(numberList , ','); } System.out.println(System.currentTimeMillis() - start); start = System.currentTimeMillis(); for(int i=0; i<1000000; i++) { Splitter.on(',').split(numberList ); } System.out.println(System.currentTimeMillis() - start);代码很简单,就是都对同一个字符串进行100万次的分隔操作,看看时间上的区别,结果如下:
983 165很明显,guava的速度快很多,这个程序如果运行在每天处理大量字符串的服务中,那么性能差异更加明显。我想其中的原因是Splitter返回的是Iterable<String>,而StringUtils.split返回的是一个String[],需要创建新的String对象,导致耗时增加。
start = System.currentTimeMillis(); Splitter s = Splitter.on(','); for (int i = 0; i < 1000000; i++) { s.split(numberList); } System.out.println(System.currentTimeMillis() - start);结果为12,神奇吧,呵呵
final String numberList = "One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten"; long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { final String[] numbers = StringUtils.split(numberList, ','); for (String number : numbers) { number.length(); } } System.out.println(System.currentTimeMillis() - start); start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { Iterable<String> is = Splitter.on(',').split(numberList); for(String s:is) { s.length(); } } System.out.println(System.currentTimeMillis() - start); start = System.currentTimeMillis(); Splitter sp = Splitter.on(','); for (int i = 0; i < 1000000; i++) { Iterable<String> is = sp.split(numberList); for(String s:is) { s.length(); } } System.out.println(System.currentTimeMillis() - start);
851 2967 2514
final String numberList = "One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten"; long strtime=System.currentTimeMillis(); numberList.split(","); System.out.println(System.currentTimeMillis()-strtime); strtime=System.currentTimeMillis(); StringUtils.split(numberList,","); System.out.println(System.currentTimeMillis()-strtime); strtime=System.curren