Java 字符替换效率比较

http://blog.csdn.net/feng88724/article/details/7974355
[java]  view plain copy print ?
  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来处理即可。



[java]  view plain copy print ?
  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.    }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值