有这么一个小事: DB表里的一个字段存着类似这样的数据">=100",">25","=123",现在要求在Java取出后把那些比较运算符后的数字取出来,比如说">=100"取出"100"来, ">123"取出"123"来.
简单想了想,觉得用subString有些麻烦, 还得借助indexOf去得到比较运算符的位置,这样也就意味着另写一个方法,这个方法直接放在model类里很ugly放到commonUtil里吧还得再把那个文件也检出... 麻烦!(这时想到了apache的StringUtils啊,不过由于是急活也没埋时间去看StringUtils下的方法), 转念想到了split方法.于是有了如下实现:
public String getRealValue(){
if(descText == null){
return "";
}
if(descText.startsWith(">=")){
return descText.split(">=")[1];
}else if(descText.startsWith(">")){
return descText.split(">")[1];
}else if(descText.startsWith("=")){
return descText.split("=")[1];
}else{
return "";
}
}
现在手头没什么急活了, 就回过头来再看看这个问题. 这次从apache的StringUtils看起.
从API里看到如下的方法: IsEmpty, IndexOf, Substring等方法, 接下来看到的substringAfter方法吸引了我的注意,这不正好符合我的问题嘛.
再看它的源码:
public static String substringAfter(String str, String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
int pos = str.indexOf(separator);
if (pos == -1) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
用的方法也就是先通过indexOf再以subString来取得最终结果.
这个方法里为什么没像我那样用split呢? 用split有什么不好?带着这种疑问我看了String中split方法的实现:
public String[] split(String regex, int limit) {
return Pattern.compile(regex).split(this, limit);
}
My God! 差老多了, 这不是杀鸡用了牛刀!
从代码量来看:new Pattern(compile方法里调用)里有15行的实现,split方法里又有35行的实现. 这时感觉到了代码行数也是对一个算法高效与否的粗略判断.
再往下追, compile方法里有new Pattern(regex, 0);
而在split里又有ArrayList matchList = new ArrayList();
我们知道new一个新的对象JVM是做不少额外开销的. 而反看substringAfter里用到的两个方法indexOf和substring,全都是char数组的操作.
这样一比较发现, split与substringAfter在算法复杂度上的差别要比用牛刀来杀鸡夸张多了.