String.format
在 Java 中使用和字符串连接之间有明显的区别吗?
我倾向于使用String.format
但偶尔会滑倒并使用串联。我想知道一个是否比另一个更好。
我看到它的方式String.format
让你在“格式化”字符串方面更有力量;并且串联意味着您不必担心不小心添加了额外的 %s 或遗漏了一个。
String.format
也更短。
哪一个更具可读性取决于您的头脑是如何工作的。
String.format
在 Java 中使用和字符串连接之间有明显的区别吗?
我倾向于使用String.format
但偶尔会滑倒并使用串联。我想知道一个是否比另一个更好。
我看到它的方式String.format
让你在“格式化”字符串方面更有力量;并且串联意味着您不必担心不小心添加了额外的 %s 或遗漏了一个。
String.format
也更短。
哪一个更具可读性取决于您的头脑是如何工作的。
我建议最好使用String.format()
. 主要原因是String.format()
可以更轻松地使用从资源文件加载的文本进行本地化,而如果不为每种语言生成具有不同代码的新可执行文件,则无法本地化连接。
如果您计划将您的应用程序本地化,您还应该养成为格式标记指定参数位置的习惯:
"Hello %1$s the time is %2$t"
然后可以将其本地化并交换名称和时间标记,而无需重新编译可执行文件以说明不同的顺序。使用参数位置,您还可以重复使用相同的参数,而无需将其两次传递给函数:
String.format("Hello %1$s, your name is %1$s and the time is %2$t", name, time)
关于性能:
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
String s = "Hi " + i + "; Hi to you " + i*2;
}
long end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond") ;
start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
String s = String.format("Hi %s; Hi to you %s",i, + i*2);
}
end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
}
计时结果如下:
因此,连接比 String.format 快得多。
由于讨论了性能,我想我会添加一个包含 StringBuilder 的比较。它实际上比 concat 更快,当然还有 String.format 选项。
为了使这成为一种苹果对苹果的比较,我在循环中而不是在外部实例化一个新的 StringBuilder (这实际上比只进行一个实例化更快,这很可能是由于在末尾为循环追加重新分配空间的开销一名建设者)。
String formatString = "Hi %s; Hi to you %s";
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = String.format(formatString, i, +i * 2);
}
long end = System.currentTimeMillis();
log.info("Format = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = "Hi " + i + "; Hi to you " + i * 2;
}
end = System.currentTimeMillis();
log.info("Concatenation = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuilder bldString = new StringBuilder("Hi ");
bldString.append(i).append("; Hi to you ").append(i * 2);
}
end = System.currentTimeMillis();
log.info("String Builder = " + ((end - start)) + " millisecond");
哪一个更具可读性取决于您的头脑是如何工作的。
你在那里得到了答案。
这是个人品味的问题。
我想,字符串连接稍微快一些,但这应该可以忽略不计。
这是一个以毫秒为单位的多个样本大小的测试。
public class Time {
public static String sysFile = "/sys/class/camera/rear/rear_flash";
public static String cmdString = "echo %s > " + sysFile;
public static void main(String[] args) {
int i = 1;
for(int run=1; run <= 12; run++){
for(int test =1; test <= 2 ; test++){
System.out.println(
String.format("\nTEST: %s, RUN: %s, Iterations: %s",run,test,i));
test(run, i);
}
System.out.println("\n____________________________");
i = i*3;
}
}
public static void test(int run, int iterations){
long start = System.nanoTime();
for( int i=0;i<iterations; i++){
String s = "echo " + i + " > "+ sysFile;
}
long t = System.nanoTime() - start;
String r = String.format(" %-13s =%10d %s", "Concatenation",t,"nanosecond");
System.out.println(r) ;
start = System.nanoTime();
for( int i=0;i<iterations; i++){
String s = String.format(cmdString, i);
}
t = System.nanoTime() - start;
r = String.format(" %-13s =%10d %s", "Format",t,"nanosecond");
System.out.println(r);
start = System.nanoTime();
for( int i=0;i<iterations; i++){
StringBuilder b = new StringBuilder("echo ");
b.append(i).append(" > ").append(sysFile);
String s = b.toString();
}
t = System.nanoTime() - start;
r = String.format(" %-13s =%10d %s", "StringBuilder",t,"nanosecond");
System.out.println(r);
}
}
TEST: 1, RUN: 1, Iterations: 1
Concatenation = 14911 nanosecond
Format = 45026 nanosecond
StringBuilder = 3509 nanosecond
TEST: 1, RUN: 2, Iterations: 1
Concatenation = 3509 nanosecond
Format = 38594 nanosecond
StringBuilder = 3509 nanosecond
____________________________
TEST: 2, RUN: 1, Iterations: 3
Concatenation = 8479 nanosecond
Format = 94438 nanosecond
StringBuilder = 5263 nanosecond
TEST: 2, RUN: 2, Iterations: 3
Concatenation = 4970 nanosecond
Format = 92976 nanosecond
StringBuilder = 5848 nanosecond
____________________________
TEST: 3, RUN: 1, Iterations: 9
Concatenation = 11403 nanosecond
Format = 287115 nanosecond
StringBuilder = 14326 nanosecond
TEST: 3, RUN: 2, Iterations: 9
Concatenation = 12280 nanosecond
Format = 209051 nanosecond
StringBuilder = 11818 nanosecond
____________________________
TEST: 5, RUN: 1, Iterations: 81
Concatenation = 54383 nanosecond
Format = 1503113 nanosecond
StringBuilder = 40056 nanosecond
TEST: 5, RUN: 2, Iterations: 81
Concatenation = 44149 nanosecond
Format = 1264241 nanosecond
StringBuilder = 34208 nanosecond
____________________________
TEST: 6, RUN: 1, Iterations: 243
Concatenation = 76018 nanosecond
Format = 3210891 nanosecond
StringBuilder = 76603 nanosecond
TEST: 6, RUN: 2, Iterations: 243
Concatenation = 91222 nanosecond
Format = 2716773 nanosecond
StringBuilder = 73972 nanosecond
____________________________
TEST: 8, RUN: 1, Iterations: 2187
Concatenation = 527450 nanosecond
Format = 10291108 nanosecond
StringBuilder = 885027 nanosecond
TEST: 8, RUN: 2, Iterations: 2187
Concatenation = 526865 nanosecond
Format = 6294307 nanosecond
StringBuilder = 591773 nanosecond
____________________________
TEST: 10, RUN: 1, Iterations: 19683
Concatenation = 4592961 nanosecond
Format = 60114307 nanosecond
StringBuilder = 2129387 nanosecond
TEST: 10, RUN: 2, Iterations: 19683
Concatenation = 1850166 nanosecond
Format = 35940524 nanosecond
StringBuilder = 1885544 nanosecond
____________________________
TEST: 12, RUN: 1, Iterations: 177147
Concatenation = 26847286 nanosecond
Format = 126332877 nanosecond
StringBuilder = 17578914 nanosecond
TEST: 12, RUN: 2, Iterations: 177147
Concatenation = 24405056 nanosecond
Format = 129707207 nanosecond
StringBuilder = 12253840 nanosecond
这是与上面相同的测试,只是在StringBuilder上调用了toString()方法。下面的结果表明,StringBuilder 方法比使用+运算符的字符串连接要慢一点。
文件:StringTest.java
class StringTest {
public static void main(String[] args) {
String formatString = "Hi %s; Hi to you %s";
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = String.format(formatString, i, +i * 2);
}
long end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = "Hi " + i + "; Hi to you " + i * 2;
}
end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuilder bldString = new StringBuilder("Hi ");
bldString.append(i).append("Hi to you ").append(i * 2).toString();
}
end = System.currentTimeMillis();
System.out.println("String Builder = " + ((end - start)) + " millisecond");
}
}
Shell 命令:(编译并运行 StringTest 5 次)
> javac StringTest.java
> sh -c "for i in \$(seq 1 5); do echo \"Run \${i}\"; java StringTest; done"
结果 :
Run 1
Format = 1290 millisecond
Concatenation = 115 millisecond
String Builder = 130 millisecond
Run 2
Format = 1265 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond
Run 3
Format = 1303 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond
Run 4
Format = 1297 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond
Run 5
Format = 1270 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond
String.format()
不仅仅是连接字符串。例如,您可以使用String.format()
.
但是,如果您不关心本地化,则没有功能差异。也许一个比另一个快,但在大多数情况下,它可以忽略不计..
一般来说,字符串连接应该优先于String.format
. 后者有两个主要缺点:
关于第 1 点,我的意思是不可能String.format()
在单个顺序传递中理解调用在做什么。一个人被迫在格式字符串和参数之间来回切换,同时计算参数的位置。对于短连接,这不是什么大问题。然而,在这些情况下,字符串连接不那么冗长。
关于第 2 点,我的意思是构建过程的重要部分以格式字符串编码(使用 DSL)。使用字符串表示代码有很多缺点。它本质上不是类型安全的,并且使语法高亮、代码分析、优化等复杂化。
当然,当使用 Java 语言外部的工具或框架时,新的因素可能会发挥作用。
我没有做过任何具体的基准测试,但我认为连接可能会更快。String.format() 创建了一个新的 Formatter,而后者又创建了一个新的 StringBuilder(大小只有 16 个字符)。这是相当大的开销,特别是如果您正在格式化较长的字符串并且 StringBuilder 必须不断调整大小。
但是,串联的用处不大,而且更难阅读。与往常一样,值得对您的代码进行基准测试,看看哪个更好。在将资源包、语言环境等加载到内存中并且代码经过 JIT 处理后,服务器应用程序中的差异可能可以忽略不计。
也许作为最佳实践,使用适当大小的 StringBuilder(可附加)和 Locale 创建自己的 Formatter 并在您有很多格式化工作时使用它是一个好主意。
可能会有明显的差异。
String.format
非常复杂,并且在下面使用正则表达式,所以不要养成在任何地方都使用它的习惯,而只在需要的地方使用它。
StringBuilder
会快一个数量级(正如这里有人已经指出的那样)。
我认为我们可以使用它,MessageFormat.format
因为它应该在可读性和性能方面都很好。
我使用了与Icaro在上述答案中使用的程序相同的程序,并通过附加代码来增强它以用于MessageFormat
解释性能数字。
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = "Hi " + i + "; Hi to you " + i * 2;
}
long end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
}
end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
}
end = System.currentTimeMillis();
System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
}
串联 = 69 毫秒
格式 = 1435 毫秒
MessageFormat = 200 毫秒
更新:
根据 SonarLint 报告,应正确使用 Printf 样式的格式字符串 (squid:S3457)
因为printf-style
格式字符串是在运行时解释的,而不是由编译器验证的,所以它们可能包含导致创建错误字符串的错误。此规则在调用、、、和类的 format(...) 方法以及或类的方法时静态验证printf-style
格式字符串与其参数的相关性。java.util.Formatter
java.lang.String
java.io.PrintStream
MessageFormat
java.io.PrintWriter
printf(...)
java.io.PrintStream
java.io.PrintWriter
我用花括号替换了 printf 样式,得到了一些有趣的结果,如下所示。
连接 = 69 毫秒
格式 = 1107 毫秒
格式:花括号 = 416 毫秒
MessageFormat = 215 毫秒
MessageFormat:花括号 = 2517 毫秒
我的结论:
正如我在上面强调的那样,使用带花括号的 String.format 应该是获得良好可读性和性能优势的不错选择。
习惯 String.Format 需要一点时间,但在大多数情况下这是值得的。在 NRA 的世界中(从不重复任何事情),将您的标记化消息(日志或用户)保存在常量库中(我更喜欢相当于静态类的内容)并在必要时使用 String.Format 调用它们非常有用,无论您是否是否本地化。尝试将此类库与连接方法一起使用时,任何需要连接的方法都难以阅读、排除故障、校对和管理。更换是一种选择,但我怀疑它的性能。经过多年的使用,我对 String.Format 的最大问题是当我将它传递给另一个函数(如 Msg)时,调用的长度很长,但使用自定义函数作为别名很容易解决.
您无法通过上面的程序比较 String Concatenation 和 String.Format 。
您也可以尝试在代码块中交换使用 String.Format 和 Concatenation 的位置,如下所示
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
for( int i=0;i<1000000; i++){
String s = String.format( "Hi %s; Hi to you %s",i, + i*2);
}
long end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for( int i=0;i<1000000; i++){
String s = "Hi " + i + "; Hi to you " + i*2;
}
end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond") ;
}
您会惊讶地发现 Format 在这里运行得更快。这是因为创建的初始对象可能不会被释放,并且内存分配和性能可能存在问题。