Java 字符替换效率比较
2012-09-25 16:44 三戒1993 阅读(175) 评论(0) 收藏 举报- public static String encode(String str) {
- if(str == null) {
- return null;
- }
- str = str.replace('+', '~');
- str = str.replace('/', '_');
- str = str.replace('=', '.');
- return str;
- }
- public static String encode2(String str) {
- if(str == null) {
- return null;
- }
- str = str.replace("+", "~");
- str = str.replace("/", "_");
- str = str.replace("=", ".");
- return str;
- }
- public static String encode3(String str) {
- if(str == null) {
- return null;
- }
- char[] array = str.toCharArray();
- for (int i = 0, length = array.length; i < length; i++) {
- if(array[i] == '+') {
- array[i] = '~';
- } else if(array[i] == '/') {
- array[i] = '_';
- } else if(array[i] == '=') {
- array[i] = '.';
- }
- }
- return new String(array);
- }
写了如上三个方法,3个方法都能达到字符替换的效果,但是效率不一样;第一种、第二种方式都是遍历三遍, 第三种遍历一遍;
测试字符串为:
String str = "asdasddasd+asd/asdadas======asdasd++++++++//===kkkklakdjfh";
执行1000000次,结果为:
3031
51706
1401
第三种数组的效率最高啊;
测试字符串为:
String str = "asdasddasdasdasddasdasdasddasdasdasddasdasdasddasdasdasddasdasdasddasd";
执行1000000次,结果为:
1169
22874
1496
第一种replace的效率反而高了。
原因是replace方法会先去查找字符串中是否包含需要替换的字符,如果没有就直接返回了,有才会去遍历替换(下面是replace源码,有兴趣的可以看下); 所以当目标字符串中不包含需要替换的字符时,replace效率最高;
在日常开发中,就不要折腾了,直接调用replace来处理即可。
- public String replace(char oldChar, char newChar) {
- if (oldChar != newChar) {
- int len = count;
- int i = -1;
- char[] val = value; /* avoid getfield opcode */
- int off = offset; /* avoid getfield opcode */
- while (++i < len) {
- if (val[off + i] == oldChar) {
- break;
- }
- }
- if (i < len) {
- char buf[] = new char[len];
- for (int j = 0 ; j < i ; j++) {
- buf[j] = val[off+j];
- }
- while (i < len) {
- char c = val[off + i];
- buf[i] = (c == oldChar) ? newChar : c;
- i++;
- }
- return new String(0, len, buf);
- }
- }
- return this;
- }