这篇文章主要讲解了Java字符串拼接效率的测试,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

测试代码:
public class StringJoinTest {
public static void main(String[] args) {
int count = 10000;
long begin, end, time;
begin = System.currentTimeMillis();
testString(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("拼接" + count + "次,String消耗时间:" + time + "毫秒");
begin = System.currentTimeMillis();
testStringBuffer(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("拼接" + count + "次,StringBuffer消耗时间:" + time + "毫秒");
begin = System.currentTimeMillis();
testStringBuilder(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("拼接" + count + "次,StringBuilder消耗时间:" + time + "毫秒");
}
private static String testStringBuilder(int count) {
StringBuilder tem = new StringBuilder();
for (int i = 0; i < count; i++) {
tem.append("hello world!");
}
return tem.toString();
}
private static String testStringBuffer(int count) {
StringBuffer tem = new StringBuffer();
for (int i = 0; i < count; i++) {
tem.append("hello world!");
}
return tem.toString();
}
private static String testString(int count) {
String tem = "";
for (int i = 0; i < count; i++) {
tem += "hello world!";
}
return tem;
}
}另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。