你真的会拼接字符串吗?

编程入门 行业动态 更新时间:2024-10-22 23:37:15

<a href=https://www.elefans.com/category/jswz/34/1764663.html style=你真的会拼接字符串吗?"/>

你真的会拼接字符串吗?

直接上菜:

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)

上面代码编译后的样子:

结论:

  1. 其实效率最高的是通过StringBuilder来拼接,但我们常写的代码 a + b这种方式编译器会自动转换为StringBuilder的方式,所以以后如果有人怼你说不用直接拼接字符串,则可以直接怼回去了。就是代码看起来有点不优雅。
  2. String.format的方式不建议使用
  3. 如果你喜欢像打印日志一样使用{}占位符,则推荐使用slf4j自带的MessageFormatter.format方法

原文连接

更多推荐

你真的会拼接字符串吗?

本文发布于:2023-11-15 00:59:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1590866.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:你真   字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!