Java的.replace()优化(重写)

说明:今天刚好看到一篇重写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 

上述代码测试并未穷尽,开发过程中请谨慎使用

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值