说明:今天刚好看到一篇重写replace性能提升了10倍的文章,里面的replace方法改造我觉得挺有意思,而且性能提升很夸张,我一看就心动了,代码我做了下改造比较贴近我们常用的.replace()替换方法,直接上代码。
public class StringUtils {
public static String replace(String content,String oldChar, String newChar){
int beginIndex = 0;
int endIndex = 0;
StringBuffer stringBuffer = new StringBuffer();
if(isNotEmpty(content)&&isNotEmpty(oldChar)){
int len = oldChar.length();
beginIndex = content.indexOf(oldChar,0);
if(beginIndex>0){
stringBuffer.append(content,0,beginIndex);
}
stringBuffer.append(newChar);
while (beginIndex !=-1){
endIndex = content.indexOf(oldChar,beginIndex+len);
if(endIndex == -1){
stringBuffer.append(content.substring(beginIndex+len));
beginIndex=-1;
continue;
}
stringBuffer.append(content,beginIndex+len,endIndex);
stringBuffer.append(newChar);
beginIndex = content.indexOf(oldChar,endIndex+len);
if(beginIndex-endIndex>=1){
stringBuffer.append(content,endIndex+len,beginIndex);
stringBuffer.append(newChar);
}
}
if(endIndex!=-1){
stringBuffer.append(content.substring(endIndex+len));
}
}else{
return content;
}
return stringBuffer.toString();
}
public static void main(String[] args) {
String content = "这里文本内容尽量复杂,能看到效果更好,下面替换的字符串自行修改...";
long s = System.currentTimeMillis();
content.replace("的","滴").replace("我","你");
long e = System.currentTimeMillis();
//传统替换消耗时间
System.out.println(e-s);
replace(replace(content,"的","滴"),"我","你");
//改写后替换消耗时间
System.out.println(System.currentTimeMillis()-e);
}
}
这个优化效果还是挺强大的,比如上述main中的content内容越大,替换的字符串出现频次越多,执行后打印出来的时间基数差距越大,经测试content长度2000字符(2篇文章)替换同样的常见字符,打印出的耗时:前值 5 后值 2
上述代码测试并未穷尽,开发过程中请谨慎使用