文字替换之效率

1. 常用方法


 a) public String replace(char oldChar, char newChar) (文本)

 b) public String replace(CharSequence target, CharSequence replacement)(文本)

 c) public String replaceAll(String regex, String replacement) (表达式)

 d) commons-lang-2.1:org.apache.commons.lang.StringUtils(文本)

 e) Matcher.replaceAll(String replacement)(表达式)

 

2. 小误差验证

 

int count = 10*10000;
String str = "127.0.0.1";
{
	System.out.print(str.replace('.', '_'));
	long b = System.nanoTime();
	for (int i = 0; i < count; i++) {
		str.replace('.', '_');
	}
	System.out.println("  basic-char  :"+(System.nanoTime()-b));

}
{
	System.out.print(str.replace(".", "_"));
	long b = System.nanoTime();
	for (int i = 0; i < count; i++) {
		str.replace("\\.", "_");
	}
	System.out.println("  CharSequence:"+(System.nanoTime()-b));
}

{
	System.out.print(str.replaceAll("\\.", "_"));
	long b = System.nanoTime();
	for (int i = 0; i < count; i++) {
		str.replaceAll("\\.", "_");
	}
	System.out.println("  replaceAll  :"+(System.nanoTime()-b));
}

{
	//commons-lang-2.1:org.apache.commons.lang.StringUtils
	System.out.print(StringUtils.replace(str, ".", "_"));
	long b = System.nanoTime();
	for (int i = 0; i < count; i++) {
		StringUtils.replace(str, ".", "_");
	}
	System.out.println("  StringUtils :"+(System.nanoTime()-b));
}

{
	Matcher m = Pattern.compile(".", Pattern.LITERAL).matcher(str);
	System.out.print(m.replaceAll("_"));
	long b = System.nanoTime();
	for (int i = 0; i < count; i++) {
		m.reset();
		m.replaceAll("_");
	}
	System.out.println(" *CharSequence:"+(System.nanoTime()-b));
}

{
	Matcher m = Pattern.compile("\\.").matcher(str);
	System.out.print(m.replaceAll("_"));
	long b = System.nanoTime();
	for (int i = 0; i < count; i++) {
		m.reset();
		m.replaceAll("_");
	}
	System.out.println(" *REGEXP      :"+(System.nanoTime()-b));
}

 

3. 鲁莽结论
输出

127_0_0_1 basic-char :9919554
127_0_0_1 CharSequence:73282416
127_0_0_1 replaceAll :209326220
127_0_0_1 StringUtils :69380801
127_0_0_1 *CharSequence:160218838
127_0_0_1 *REGEXP :158787441

 

结论

 

basic-char >> (StringUtils ≈ CharSequence)>> REGEXP >replaceAll

 

4. 注意事项

 

参数为正则表达式的时候,需要字符转义,如 ^.$?*+等

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值