Java字符串模板格式化汇总8法(附性能对比)

Java字符串模板格式化汇总8法(附性能对比)

 

结论: 

1. 循环中, 不要用+进行字符串拼接, 而用StringBuilder.append()方法

2. 非循环中, 字符串拼接使用+性能最高, 其次是StringBuilder.append()方法

 

 

 

 

 

1. ++

对于初学JAVA的蒙童,大约都会使用这招

@Test
public void testAdd(){

    Date now = new Date();

    String yearMonth = DateUtil.toString(now, DatePattern.YEAR_AND_MONTH);
    String expressDeliveryType = "sf";
    String fileName = DateUtil.toString(now, DatePattern.TIMESTAMP);

    String template = "/home/expressdelivery/" + yearMonth + "/" + expressDeliveryType + "/vipQuery_" + fileName + ".log";

    System.out.println(template);
}

输出 :

/home/expressdelivery/2017-07/sf/vipQuery_20170723042314.log

2. StringBuffer / StringBuilder

@Test
public void testStringBuilder(){

    Date now = new Date();

    String yearMonth = DateUtil.toString(now, DatePattern.YEAR_AND_MONTH);
    String expressDeliveryType = "sf";
    String fileName = DateUtil.toString(now, DatePattern.TIMESTAMP);

    StringBuilder sb = new StringBuilder();
    sb.append("/home/expressdelivery/");
    sb.append(yearMonth);
    sb.append("/");
    sb.append(expressDeliveryType);
    sb.append("/vipQuery_");
    sb.append(fileName);
    sb.append(".log");

    String template = sb.toString();

    System.out.println(template);
}

输出 :

/home/expressdelivery/2017-07/sf/vipQuery_20170723042603.log

缺点:

  • 代码太长了

3. StringUtil.format(String, Object…​)

使用 com.feilong.core.lang.StringUtil.format(String, Object…​)

内部封装了 String.format(String, Object)

@Test
public void testStringFormat(){
    Date now = new Date();

    String yearMonth = DateUtil.toString(now, DatePattern.YEAR_AND_MONTH);
    String expressDeliveryType = "sf";
    String fileName = DateUtil.toString(now, DatePattern.TIMESTAMP);

    String template = StringUtil.format("/home/expressdelivery/%s/%s/vipQuery_%s.log", yearMonth, expressDeliveryType, fileName);

    System.out.println(template);
}

输出 :

/home/expressdelivery/2017-07/sf/vipQuery_20170723043153.log

4. MessageFormatUtil.format(String, Object…​)

使用 com.feilong.core.text.MessageFormatUtil.format(String, Object…​)

内部封装了 java.text.MessageFormat.format(String, Object…​)

@Test
public void testMessageFormat(){
    Date now = new Date();

    String yearMonth = DateUtil.toString(now, DatePattern.YEAR_AND_MONTH);
    String expressDeliveryType = "sf";
    String fileName = DateUtil.toString(now, DatePattern.TIMESTAMP);

    String template = MessageFormatUtil
                    .format("/home/expressdelivery/{0}/{1}/vipQuery_{2}.log", yearMonth, expressDeliveryType, fileName);

    System.out.println(template);
}

输出 :

/home/expressdelivery/2017-07/sf/vipQuery_20170723043153.log

5. Slf4jUtil.format(String, Object…​)

使用 com.feilong.tools.slf4j.Slf4jUtil.format(String, Object…​)

借助 slf4j 日志占位符

@Test
public void testSlf4jFormat(){
    Date now = new Date();

    String yearMonth = DateUtil.toString(now, DatePattern.YEAR_AND_MONTH);
    String expressDeliveryType = "sf";
    String fileName = DateUtil.toString(now, DatePattern.TIMESTAMP);

    String template = Slf4jUtil.format("/home/expressdelivery/{}/{}/vipQuery_{}.log", yearMonth, expressDeliveryType, fileName);

    System.out.println(template);
}

输出:

/home/expressdelivery/2017-07/sf/vipQuery_20170723144236.log

6. StringUtil.replace(CharSequence, Map<String, V>)

使用 com.feilong.core.lang.StringUtil.replace(CharSequence, Map<String, V>)

内部封装了 apache commons-lang3 org.apache.commons.lang3.text.StrSubstitutor , 现在叫 commons-text

使用给定的字符串 templateString 作为模板,解析匹配的变量 .

@Test
public void testReplace(){
    Date date = new Date();
    Map<String, String> map = new HashMap<>();
    map.put("yearMonth", DateUtil.toString(date, YEAR_AND_MONTH));
    map.put("expressDeliveryType", "sf");
    map.put("fileName", DateUtil.toString(date, TIMESTAMP));

    String template = StringUtil.replace("/home/expressdelivery/${yearMonth}/${expressDeliveryType}/vipQuery_${fileName}.log", map);

    System.out.println(template);
}

输出:

/home/expressdelivery/2017-07/sf/vipQuery_20170723144608.log

优点:

  • 模块可以定义变量名字了,不怕混乱

Note

此方法只能替换字符串,而不能像el表达式一样使用对象属性之类的来替换

7. VelocityUtil.parseString(String, Map<String, ?>)

使用 com.feilong.tools.velocity.VelocityUtil.parseString(String, Map<String, ?>)

该方法需要 jar

<dependency>
  <groupId>com.feilong.platform.tools</groupId>
  <artifactId>feilong-tools-velocity</artifactId>
  <version>${version.feilong-platform}</version>
</dependency>
@Test
public void testVelocityParseString(){
    Date date = new Date();

    Map<String, String> map = new HashMap<>();
    map.put("yearMonth", DateUtil.toString(date, YEAR_AND_MONTH));
    map.put("expressDeliveryType", "sf");
    map.put("fileName", DateUtil.toString(date, TIMESTAMP));

    VelocityUtil velocityUtil = new VelocityUtil();

    String template = velocityUtil
                    .parseString("/home/expressdelivery/${yearMonth}/${expressDeliveryType}/vipQuery_${fileName}.log", map);

    System.out.println(template);
}

输出

/home/expressdelivery/2017-07/sf/vipQuery_20170723145856.log

8. VelocityUtil.parseTemplateWithClasspathResourceLoader(String, Map<String, ?>)

使用 com.feilong.tools.velocity.VelocityUtil.parseTemplateWithClasspathResourceLoader(String, Map<String, ?>)

该方法需要 jar

<dependency>
  <groupId>com.feilong.platform.tools</groupId>
  <artifactId>feilong-tools-velocity</artifactId>
  <version>${version.feilong-platform}</version>
</dependency>

该方法适合于 字符串模板独立成文件, 方便维护

路径是classpath 下面, 比如 velocity/path.vm

28497395 a52f617c 6fb8 11e7 9902 66249985242a

此时代码需要如此调用:

@Test
public void testVelocityParseTemplateWithClasspathResourceLoader(){
    Date date = new Date();

    Map<String, String> map = new HashMap<>();
    map.put("yearMonth", DateUtil.toString(date, YEAR_AND_MONTH));
    map.put("expressDeliveryType", "sf");
    map.put("fileName", DateUtil.toString(date, TIMESTAMP));

    VelocityUtil velocityUtil = new VelocityUtil();

    String template = velocityUtil.parseTemplateWithClasspathResourceLoader("velocity/path.vm", map);

    System.out.println(template);
}

输出 :

/home/expressdelivery/2017-07/sf/vipQuery_20170723150443.log

9. 性能对比

28501853 87f4c8c2 7017 11e7 99db 3b2d47c803a8

上图是 分别循环 100000, 500000, 1000000, 2000000 统计出来的数据

在性能上 String format 是最差的

字符串 ++ 最快, StringBuilder 次之 , slf4j 的格式化再次之

测试硬件概览:

型号名称:	MacBook Pro
处理器名称:	Intel Core i5
处理器速度:	2.9 GHz
内存:	16 GB

10. 参考

 

 

转载:

Java字符串模板格式化汇总8法(附性能对比) - 飞天奔月的个人空间 - OSCHINA
https://my.oschina.net/venusdrogon/blog/1486633

 

 

 

 

 

 

 

========================================================================

========================================================================

========================================================================

 

 

字符串连接你用+还是用StringBuilder - 掘金
https://juejin.im/post/5b2af17de51d4558c713507c#heading-2

 

 

 

 

 

 

字符串连接你用+还是用StringBuilder

前言

据我所知字符串确实已经成为 Java 开发人员最常用的类了,而且是大量使用。我们都知道,String 其实是封装了字符,所以俩字符串连接就是将字符串对象里面的字符连起来。很多人习惯使用+来连接字符串,也有人会用 StringBuilder 的append方法。

"+"编译后

看看如果我们在程序中直接使用+来连接字符串的情况,用下面一个简单的例子来说明,进行两个字符串连接操作,即s3 = s1 + s2

public class TestString {
	public static void main(String[] args) {
		String s1 = "www";
		String s2 = "ccc";
		String s3 = s1 + s2;
	}
}
复制代码

接着javap -c TestString.class看一下编译后的情况,可以看到编译器其实是对+进行了转换的,转成了 StringBuilder 对象来操作了,首先使用 s1 创建 StringBuilder 对象,然后用 append方法连接 s2,最后调用toString方法完成。

public class com.seaboat.string.TestString {
  public com.seaboat.string.TestString();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: ldc           #16                 // String www
       2: astore_1
       3: ldc           #18                 // String ccc
       5: astore_2
       6: new           #20                 // class java/lang/StringBuilder
       9: dup
      10: aload_1
      11: invokestatic  #22                 // Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
      14: invokespecial #28                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
      17: aload_2
      18: invokevirtual #31                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      21: invokevirtual #35                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      24: astore_3
      25: return
}
复制代码

"+"与"append"等价吗

前面可以看到+在编译器作用下都会转成 StringBuilder 的append方法执行,所以如果抛开运行效率来说,它们其实本质是一样的。

本质一样是否就能说明它们时等价的呢?或者说能否为了方便直接用+来连接字符串,剩下的事就交给编译器了?继续看个例子,在这个例子中有个 for 循环进行字符串连接操作。

public class TestString2 {
	public static void main(String[] args) {
		String s = "www";
		for (int i = 0; i < 10; i++)
			s += i;
	}
}
复制代码

编译后的情况如下,不熟悉指令没关系,我们只看重要的部分,if_icmplt 8,这个就是 for 循环的条件判断,小于10则不断跳到8的位置,8后面其实就是创建 StringBuilder 对象,并以本地变量s的值初始化该对象,接着再将本地变量i append到 StringBuilder 对象中,最后调用toString方法将所得值存到本地变量s。

这样来看循环中每次都要创建 StringBuilder 对象,而且要调用toString方法,这样的执行效率显然比较低,而且增加了 GC 的压力。

public class com.seaboat.string.TestString2 {
  public com.seaboat.string.TestString2();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: ldc           #16                 // String www
       2: astore_1
       3: iconst_0
       4: istore_2
       5: goto          30
       8: new           #18                 // class java/lang/StringBuilder
      11: dup
      12: aload_1
      13: invokestatic  #20                 // Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
      16: invokespecial #26                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
      19: iload_2
      20: invokevirtual #29                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
      23: invokevirtual #33                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      26: astore_1
      27: iinc          2, 1
      30: iload_2
      31: bipush        10
      33: if_icmplt     8
      36: return
}
复制代码

友好写法

把事情都丢给编译器是不友好的,为了能让程序执行更加高效,最好是我们自己来控制 StringBuilder 的实例,比如下面,只创建一个 StringBuilder 实例,后面用append方法连接字符串。

public class TestString3 {
	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder("www");
		for (int i = 0; i < 10; i++)
			sb.append(i);
	}
}
复制代码

编译后的情况如下,首先创建一个 StringBuilder 对象,使用字符串"www"来实例化该对象,接着循环调用append方法将本地变量i添加到 StringBuilder 对象中。

public class com.seaboat.string.TestString3 {
  public com.seaboat.string.TestString3();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: new           #16                 // class java/lang/StringBuilder
       3: dup
       4: ldc           #18                 // String www
       6: invokespecial #20                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
       9: astore_1
      10: iconst_0
      11: istore_2
      12: goto          24
      15: aload_1
      16: iload_2
      17: invokevirtual #23                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
      20: pop
      21: iinc          2, 1
      24: iload_2
      25: bipush        10
      27: if_icmplt     15
      30: return
}
复制代码

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值