java-字符串拼接几种方法的性能比较
一、测试方法:
String.format();
MessageFormat.format();
StringBuilder();
二、测试结果:
性能:StringBuilder > MessageFormat > String
三、运行结果:
++++++++++++++++++++++++
times=100000
String.format 耗时:660
MessageFormat.format 耗时:247
StringBuilder 耗时:4
++++++++++++++++++++++++
times=1000000
String.format 耗时:2128
MessageFormat.format 耗时:829
StringBuilder 耗时:7
++++++++++++++++++++++++
times=10000000
String.format 耗时:13809
MessageFormat.format 耗时:5823
StringBuilder 耗时:77
四、测试代码:
public static void main (String[] args){
int[] arr = new int[]{100000,1000000,10000000};
long begin=0;
long end=0;
for(int item:arr){
System.out.println("++++++++++++++++++++++++");
System.out.println("times="+item);
//String.format
begin = System.currentTimeMillis();
for(int i=0;i<item;i++){
String s = String.format("%s,%s,%s,%s","1111","2222","3333","4444");
}
end = System.currentTimeMillis();
System.out.println("String.format 耗时:"+(end-begin));
//MessageFormat
begin = System.currentTimeMillis();
for(int i=0;i<item;i++){
String s = MessageFormat.format("{0},{1},{2},{3}","1111","2222","3333","4444");
}
end = System.currentTimeMillis();
System.out.println("MessageFormat.format 耗时:"+(end-begin));
//stringformat
begin = System.currentTimeMillis();
StringBuilder sbd;
for(int i=0;i<item;i++){
sbd = new StringBuilder();
String s = sbd.append("1111").append(",")
.append("2222").append(",")
.append("3333").append(",")
.append("4444").toString();
}
end = System.currentTimeMillis();
System.out.println("StringBuilder 耗时:"+(end-begin));
}
}
标签:java,String,format,StringBuilder,System,MessageFormat,耗时,拼接,字符串 From: https://blog.51cto.com/u_4518216/5804847