首页  

字符串格式化性能对比     所属分类 java 浏览量 738
最简单的字符串相加    性能最好
slf4j MessageFormatter 使用 indexOf 解析占位符 然后拼接参数  性能较好
jdk String.format  功能强大 使用正则解析占位符 性能最差

3种方式的耗时
151 289 1975
61 464 776
15 196 743
16 101 714
16 101 707
16 101 723
16 100 737
16 101 725
17 110 733
16 107 812
17 103 731
16 102 724
17 104 727


测试代码 import java.time.LocalDateTime; import org.slf4j.helpers.MessageFormatter; public class StringFormatPerfTest { private static final int COUNT = 1000000; private static final String JDK_FORMAT = "now time is %s"; private static final String SLF4J_FORMAT = "now time is {}"; public static void main(String[] args) throws Exception { while (true) { run(); } } private static String format(String format, Object... args) { return MessageFormatter.arrayFormat(format, args).getMessage(); } private static void run() { String now = LocalDateTime.now().toString(); long start = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { format(SLF4J_FORMAT, now); } long end = System.currentTimeMillis(); long slf4jTime = end - start; start = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { String.format(JDK_FORMAT, now); } end = System.currentTimeMillis(); long jdkTime = end - start; start = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { String str = "now time is " + now; } end = System.currentTimeMillis(); long time = end - start; System.out.println(time + " " + slf4jTime + " " + jdkTime); } }
完整代码 https://gitee.com/dyyx/springboothello/blob/master/src/main/java/log/StringFormatPerfTest.java
string format几种方式

上一篇     下一篇
springboot 加载指定的 properties文件

Java8 Stream过滤null值

string format几种方式

单元测试 AIR 和 FIRST 原则

SimpleDateFormat并发问题实例演示

云服务器jdk8安装