private static String escape(String input, char[] escapeChar, StringBuilder buffer) { buffer.setLength(0); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); for (int j = 0; j < escapeChar.length; j++) { if (escapeChar[j] == c) { buffer.append('//'); break; } } buffer.append(c); } return buffer.toString(); } private static void batchTest(Callable<String>... tests) { for (Callable<String> callable : tests) { long st = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { try { callable.call(); } catch (Exception e) { e.printStackTrace(); } } System.out.println(System.currentTimeMillis() - st); try { System.out.println("result=" + callable.call()); } catch (Exception e) { e.printStackTrace(); } } } @SuppressWarnings("unchecked") public static void main(String[] args) { final StringBuilder buf = new StringBuilder(); final String s = "asdf[c1|c2]sd[c3]sdf[c4]"; batchTest(new Callable<String>() { public String call() throws Exception { return s.replace("[", "//[").replace("]", "//]").replace("|", "//|"); } }, new Callable<String>() { public String call() throws Exception { return s.replaceAll("//[|//]|//|", "$0"); } }, new Callable<String>() { public String call() throws Exception { return escape(s, new char[] { '[', ']', '|' }, buf); } }, new Callable<String>() { 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来替换字符串,如果是转义字符串的话还是自己写吧~哈哈