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; }}
测试结果:



结论:
在少量字符串拼接时还看不出差别,但随着数量的增加,String+拼接效率显著降低。在达到100万次,我本机电脑已经无法执行String+拼接了,StringBuilder效率略高于StringBuffer。所以在开发过程中通常情况下推荐使用StringBuilder。
StringBuffer和StringBuilder的区别在于StringBuffer是线程安全的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章:
1. vue cli3.0打包上线静态资源找不到路径的解决操作2. .NET的基元类型包括什么及Unmanaged和Blittable类型详解3. Intellij IDEA如何去掉@Autowired 注入警告的方法4. SpringBoot + Vue 项目部署上线到Linux 服务器的教程详解5. 初学者如何快速搭建Express开发系统步骤详解6. 详解JavaScript是如何验证URL的7. phpstorm恢复删除文件的方法8. python GUI库图形界面开发之PyQt5中QWebEngineView内嵌网页与Python的数据交互传参详细方法实例9. 关于ajax异步访问数据的问题10. 使用IDEA编写jsp时EL表达式不起作用的问题及解决方法

网公网安备