@Test
public void testFormat(){
Integer loop = 1000000;
Integer timeScale = 1000*1000;
long time = System.nanoTime();
for(int i=0;i<loop;i++){
String s = "hello "+ i +"word";
int size = s.length();
}
time = System.nanoTime() - time;
System.out.println("加号拼接: "+time+"ns"+"\t"+time/timeScale+"ms");
time = System.nanoTime();
for(int i=0;i<loop;i++){
StringBuilder s = new StringBuilder();
s.append("hello ").append(i).append("word");
int size = s.length();
}
time = System.nanoTime() - time;
System.out.println("使用Builer:"+time+"ns"+"\t"+time/timeScale+"ms");
time = System.nanoTime();
for(int i=0;i<loop;i++){
String s = String.format("%s %d %s","hello",i,"word");
int size = s.length();
}
time = System.nanoTime() - time;
System.out.println("使用format:"+time+"ns"+"\t"+time/timeScale+"ms");
}
输出结果:
#10000
加号拼接: 5066970ns 5ms
使用Builer:4961695ns 4ms
使用format:94398046ns 94ms
#100000
加号拼接: 32604006ns 32ms
使用Builer:11622116ns 11ms
使用format:401532390ns 401ms
#1000000
加号拼接: 86900437ns 86ms
使用Builer:51769362ns 51ms
使用format:2209215837ns 2209ms
可以看到加号和StringBuiler性能差不多,format方式性能差了两个数量级
950

被折叠的 条评论
为什么被折叠?



