代码改变世界

Java 字符替换效率比较

2012-09-25 16:44  三戒1993  阅读(175)  评论(0)    收藏  举报
http://blog.csdn.net/feng88724/article/details/7974355
  1. public static String encode(String str) {  
  2.     if(str == null) {  
  3.         return null;  
  4.     }  
  5.     str = str.replace('+''~');  
  6.     str = str.replace('/''_');  
  7.     str = str.replace('=''.');  
  8.     return str;  
  9. }  
  10.   
  11. public static String encode2(String str) {  
  12.     if(str == null) {  
  13.         return null;  
  14.     }  
  15.     str = str.replace("+""~");  
  16.     str = str.replace("/""_");  
  17.     str = str.replace("="".");  
  18.     return str;  
  19. }  
  20.   
  21. public static String encode3(String str) {  
  22.     if(str == null) {  
  23.         return null;  
  24.     }  
  25.     char[] array = str.toCharArray();  
  26.     for (int i = 0, length = array.length; i < length; i++) {  
  27.         if(array[i] == '+') {  
  28.             array[i] = '~';  
  29.         } else if(array[i] == '/') {  
  30.             array[i] = '_';  
  31.         } else if(array[i] == '=') {  
  32.             array[i] = '.';  
  33.         }  
  34.     }  
  35.     return new String(array);  
  36. }  


写了如上三个方法,3个方法都能达到字符替换的效果,但是效率不一样;第一种、第二种方式都是遍历三遍, 第三种遍历一遍;



测试字符串为:

String str = "asdasddasd+asd/asdadas======asdasd++++++++//===kkkklakdjfh";


执行1000000次,结果为:

3031

51706

1401


第三种数组的效率最高啊;



测试字符串为:

String str = "asdasddasdasdasddasdasdasddasdasdasddasdasdasddasdasdasddasdasdasddasd";


执行1000000次,结果为:

1169

22874

1496


第一种replace的效率反而高了。


原因是replace方法会先去查找字符串中是否包含需要替换的字符,如果没有就直接返回了,有才会去遍历替换(下面是replace源码,有兴趣的可以看下); 所以当目标字符串中不包含需要替换的字符时,replace效率最高;


在日常开发中,就不要折腾了,直接调用replace来处理即可。



  1.    public String replace(char oldChar, char newChar) {  
  2. if (oldChar != newChar) {  
  3.     int len = count;  
  4.     int i = -1;  
  5.     char[] val = value; /* avoid getfield opcode */  
  6.     int off = offset;   /* avoid getfield opcode */  
  7.   
  8.     while (++i < len) {  
  9.     if (val[off + i] == oldChar) {  
  10.         break;  
  11.     }  
  12.     }  
  13.     if (i < len) {  
  14.     char buf[] = new char[len];  
  15.     for (int j = 0 ; j < i ; j++) {  
  16.         buf[j] = val[off+j];  
  17.     }  
  18.     while (i < len) {  
  19.         char c = val[off + i];  
  20.         buf[i] = (c == oldChar) ? newChar : c;  
  21.         i++;  
  22.     }  
  23.     return new String(0, len, buf);  
  24.     }  
  25. }  
  26. return this;  
  27.    }