你真的会拼接字符串吗?
大约 2 分钟
直接上菜:
import org.slf4j.helpers.MessageFormatter;
import org.springframework.util.StopWatch;
public class PQSTest {
public static void main(String[] args) {
StopWatch stopWatch = new StopWatch("pqs");
stopWatch.start("MessageFormatter.format");
for (int i = 0; i < 10000000; i++) {
String s = MessageFormatter.format("哈哈哈 {}", i).getMessage();
}
stopWatch.stop();
stopWatch.start("String.format");
for (int i = 0; i < 10000000; i++) {
String s = String.format("哈哈哈 %d", i);
}
stopWatch.stop();
stopWatch.start("String add");
for (int i = 0; i < 10000000; i++) {
String s = "哈哈哈 " + i;
}
stopWatch.stop();
System.out.println(stopWatch.shortSummary());
System.out.println(stopWatch.prettyPrint());
}
}
执行结果截图:(jdk版本:1.8)

上面代码编译后的样子:

结论:
- 其实效率最高的是通过StringBuilder来拼接,但我们常写的代码 a + b这种方式编译器会自动转换为StringBuilder的方式,所以以后如果有人怼你说不用直接拼接字符串,则可以直接怼回去了。就是代码看起来有点不优雅。
- String.format的方式不建议使用
- 如果你喜欢像打印日志一样使用{}占位符,则推荐使用slf4j自带的MessageFormatter.format方法
系统推荐
- 记一次内存泄漏
- JVM参数设置
- 搭建基于docker的elk平台来分析java日志
- Spring Boot升级到2 6 x踩的坑
- 多台centos服务器,文件互相备份
- gperftools
- 分布式事务Seata
- 前后端常用技术
- vuepress-theme-hope 添加谷歌广告
- Docker跨主机通信方案
- MySQL数据迁移到PGSQL
- Linux
- 随机毒鸡汤:时间就像胸,挤挤就有了,躺下就没了。