java中字符串拼接 String 和 StringBuilder(StringBuffer)的使用
字符串拼接是个常用的功能,经常性使用String做字符串拼接,当拼接次数多的时候,使用String方法会消耗大量的性能和时间,因为每次String拼接时都会建立一个新的对象,随着拼接次数的增多,性能消耗、时间消耗会大量增加,这个时候应该使用StringBuilder方法。
1 public static void main(String[] args) { 2 try { 3 int count = 500; 4 5 long begin = System.currentTimeMillis(); 6 testString(count); 7 long end = System.currentTimeMillis(); 8 long time = end - begin; 9 System.out.println("String 方法拼接"+count+"次消耗时间:" + time + "毫秒"); 10 11 begin = System.currentTimeMillis(); 12 testStringBuilder(count); 13 end = System.currentTimeMillis(); 14 time = end - begin; 15 System.out.println("StringBuilder 方法拼接"+count+"次消耗时间:" + time + "毫秒"); 16 17 } catch (Exception e) { 18 e.printStackTrace(); 19 } 20 21 } 22 23 private static String testString(int count) { 24 String result = ""; 25 26 for (int i = 0; i < count; i++) { 27 result += "hello "; 28 } 29 30 return result; 31 } 32 33 private static String testStringBuilder(int count) { 34 StringBuilder sb = new StringBuilder(); 35 36 for (int i = 0; i < count; i++) { 37 sb.append("hello"); 38 } 39 40 return sb.toString(); 41 }
运行结果:
String 方法拼接500次消耗时间:2毫秒
StringBuilder 方法拼接500次消耗时间:0毫秒
String 方法拼接50000次消耗时间:4973毫秒
StringBuilder 方法拼接50000次消耗时间:3毫秒
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 协程本质是函数加状态机——零基础深入浅出 C++20 协程
· 编码之道,道心破碎。
· 记一次 .NET 某发证机系统 崩溃分析
· 微服务架构学习与思考:SOA架构与微服务架构对比分析
· tomcat为什么假死了
· 知名开源项目Alist被收购!惹程序员众怒,开团炮轰甲方
· 突发,小红书开发者后门被破解?!
· 历时半年,我将一个大型asp.net的零代码快速开发平台转成了java
· [原创]《C#高级GDI+实战:从零开发一个流程图》第03章:画一个线,连接两个矩形!
· C# 将 CSV 转化为 Excel