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; }