速度由高到低:char[] (100ms),StringBuilder(250ms),StringBuilder + Integer.toHexString(1200ms),(100000次)
代码:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Test {
public static void main(String[] args) {
for(int j=0;j<2;j++) {
toHexTest();
}
}
private static void toHexTest() {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] r = md.digest(new String("haha").getBytes());
long t0 = System.currentTimeMillis();
int count = 1000000;
for (int i = 0; i < count; i++) {
r[0]++;
String rs = bytes2Hex(r);
}
System.out.print("StringBuilder用时:");
System.out.println(System.currentTimeMillis()-t0+"ms");
t0 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
r[0]++;
String rs2 = bytes2Hex2(r);
}
System.out.print("StringBuilder + Integer.toHexString用时:");
System.out.println(System.currentTimeMillis()-t0+"ms");
t0 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
r[0]++;
String rs3 = bytes2Hex3(r);
}
System.out.print("char[]用时:");
System.out.println(System.currentTimeMillis()-t0+"ms");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String bytes2Hex(byte[] in) {
char[] c = new char[] {'0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBuilder sb = new StringBuilder(in.length*2);
for (int i = 0; i < in.length; i++) {
sb.append(c[in[i]&0x0f]);
sb.append(c[(in[i]&0xf0)>>>4]);
}
return sb.toString();
}
private static String bytes2Hex2(byte[] r) {
StringBuilder sb = new StringBuilder(r.length*2);
for(int i = 0;i<r.length;i++) {
sb.append(Integer.toHexString(r[i]&0x0f));
}
return sb.toString();
}
private static String bytes2Hex3(byte[] in) {
char[] c = new char[] {'0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char[] sb = new char[in.length*2];
for (int i = 0; i < in.length; i++) {
sb[i++]=(c[in[i]&0x0f]);
sb[i]=(c[(in[i]&0xf0)>>>4]);
}
return new String(sb);
}
}
结果:
StringBuilder用时:261ms
StringBuilder + Integer.toHexString用时:1216ms
char[]用时:107ms
StringBuilder用时:242ms
StringBuilder + Integer.toHexString用时:1167ms
char[]用时:103ms