package com.company.danei;
/**
* @Author:
* @Date: 2021-05-09
* @Description: 验证StringBuilder的执行效率,通过StringBuilder的append()方法拼接字符串,效率比+拼接高出1000倍
**/
public class Test_StringBuilder {
public static void main(String[] args) {
String str = "abcdefghicklmnopqestuvwxyz";
method(str);
method2(str);
}
/**
* 通过StringBuilder拼接字符串,计算执行效率
* @param str
*/
private static void method2(String str) {
StringBuilder sb = new StringBuilder();
Long s1 = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
sb.append(str);
}
Long s2= System.currentTimeMillis();
System.out.println(s2-s1);//1ms
}
/**
* 通过+连接字符串
* 计算程序执行效率
* @param str
*/
private static void method(String str) {
String str1="";
Long s1 = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
str1 += str;
}
Long s2= System.currentTimeMillis();
System.out.println(s2-s1);//1445ms
}
}