private static String escape(String input, char[] escapeChar, StringBuilder buffer) { buffer.setLength(0); for (int i = 0; i ... tests) { for (Callable callable : tests) { long st = System.currentTimeMillis(); for (int i = 0; i () { public String call() throws Exception { return s.replace("[", "\\[").replace("]", "\\]").replace("|", "\\|"); } }, new Callable() { public String call() throws Exception { return s.replaceAll("\\[|\\]|\\|", "\\\\$0"); } }, new Callable() { public String call() throws Exception { return escape(s, new char[] { '[', ']', '|' }, buf); } }, new Callable() { public String call() throws Exception { return StringUtils.replaceEach(s, new String[] { "[", "]", "|" }, new String[] { "\\[", "\\]", "\\|" }); } }); } 测试结果:
1047
result=asdf\[c1\|c2\]sd\[c3\]sdf\[c4\]
891
result=asdf\[c1\|c2\]sd\[c3\]sdf\[c4\]
78
result=asdf\[c1\|c2\]sd\[c3\]sdf\[c4\]
578
result=asdf\[c1\|c2\]sd\[c3\]sdf\[c4\]
--------------------------------------------------
现象:replaceAll的效率在多个频繁替换下还是可以用的,但是如果真的很多的话,不会有人不断的replace().replace()...这样吧;
再看正则和apache stringutil的replace相比又慢了许多;
结论:对于替换多个字符串的话,推荐使用apache的stringutil来替换字符串,如果是转义字符串的话还是自己写吧~哈哈
1047
result=asdf\[c1\|c2\]sd\[c3\]sdf\[c4\]
891
result=asdf\[c1\|c2\]sd\[c3\]sdf\[c4\]
78
result=asdf\[c1\|c2\]sd\[c3\]sdf\[c4\]
578
result=asdf\[c1\|c2\]sd\[c3\]sdf\[c4\]
--------------------------------------------------
现象:replaceAll的效率在多个频繁替换下还是可以用的,但是如果真的很多的话,不会有人不断的replace().replace()...这样吧;
再看正则和apache stringutil的replace相比又慢了许多;
结论:对于替换多个字符串的话,推荐使用apache的stringutil来替换字符串,如果是转义字符串的话还是自己写吧~哈哈