Java:Integer.toString()方法比将空字符串添加到整数类型值更好吗?

Jon*_*wak 1 java

可能重复:
使用(""+ <int value>)不良做法转换为String?

我正在使用PMD规则测试一些Java代码.效率的一个规则是'AddingEmptyString'.以下是该规则的说明.

查找正在添加的空字符串文字.这是将任何类型转换为String的低效方法.

    String s = "" + 123; // bad 
    String t = Integer.toString(456); // ok 
Run Code Online (Sandbox Code Playgroud)

你能解释为什么Integer.toString比将空字符串添加到整数类型值更好吗?

Geo*_*edy 6

这很糟糕,因为第一种方式比第二种方式做更多的操作.编译器会将第一行转换为等效的

String s = "" + Integer.toString(123);
Run Code Online (Sandbox Code Playgroud)

与之相比,它具有额外的字符串连接

String t = Integer.toString(456);
Run Code Online (Sandbox Code Playgroud)

即使编译器使用空字符串优化连接,当显式使用Integer.toString时,代码行的目的也更加清晰.

  • 实际上""+ 123最终成为一个新的StringBuilder().append("").append(123).toString(). (2认同)