Google的Guava工具类splitter和apache stringutil对比 编辑

时间:2021-07-26 23:05:48

一直用的是apache的stringutil工具类,其实google的工具类项目 guava中居然也有字符串的分隔类splitter的,在 http://code.google.com/p/guava-libraries/中可以下载,其中在老外的 http://www.javacodegeeks.com/2012/12/guava-splitter-vs-stringutils.html 这篇文章中进行了stringutil的对比:

首先看两者的用法:

    // Apache StringUtils...
String[] tokens1 = StringUtils.split("one,two,three",','); // Guava splitter...
Iterable<String> tokens2 = Splitter.on(',').split("one,two,three");

 StringUtils静态类来的,spiltter的语法中则要new对象,但splitter中,一个优点
是,可以去掉多余的空格等,比如:

    Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();  

            Iterable<String> tokens3 = splitter.split("one,,two,three");
Iterator<String> iterator = tokens3.iterator();
while (iterator.hasNext()) {
String value = iterator.next();
System.out.println(value);
}

输出结果是:.

    one
two
three

这个则比较方便。要注意的是splitter返回的是Iterable<String>,这个和StringUtil
有点不同。

效率方面的对比,作者作了比较:

    final String numberList = "One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten";
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringUtils.split(numberList,',');
}
System.out.print("StringUtils split expenditure time : ");
System.out.println(System.currentTimeMillis() - startTime); startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
Splitter.on(',').split(numberList);
}
System.out.print("Splitter split expenditure time : ");
System.out.println(System.currentTimeMillis() - startTime);

输出结果:

    StringUtils split expenditure time : 672
Splitter split expenditure time : 312

splitter快上!主要是怀疑因为splitter返回的是Iterable<String>,不用每次new String对象。

再来一个测试:

    final String numberList = "One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten";
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
final String[] numbers = StringUtils.split(numberList,',');
for (String number : numbers) {
number.length();
}
}
System.out.print("StringUtils split expenditure time : ");
System.out.println(System.currentTimeMillis() - startTime); Splitter splitter = Splitter.on(',');
startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
Iterable<String> numbers = splitter.split(numberList);
for (String number : numbers) {
number.length();
}
}
System.out.print("Splitter split expenditure time : ");
System.out.println(System.currentTimeMillis() - startTime);

结果如下:

    StringUtils split expenditure time : 735
Splitter split expenditure time : 2062

spitter这次更慢了! 所以感觉,如果StringUtil够用的话,其实用StringUtil其实很好的拉。