在 Java 中使用 String.format 而不是字符串连接是更好的做法吗?

新手上路,请多包涵

在 Java 中使用 String.format 和字符串连接之间有明显的区别吗?

我倾向于使用 String.format 但偶尔会滑倒并使用串联。我想知道一个是否比另一个更好。

在我看来, String.format 为您提供了更多“格式化”字符串的能力;连接意味着您不必担心不小心放入额外的 %s 或遗漏一个。

String.format 也更短。

哪一个更具可读性取决于你的头脑是如何工作的。

原文由 Omar Kooheji 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

我建议最好使用 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)

原文由 workmad3 发布,翻译遵循 CC BY-SA 3.0 许可协议

关于性能:

 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");
}

计时结果如下:

  • 串联 = 265 毫秒
  • 格式 = 4141 毫秒

因此,连接比 String.format 快得多。

原文由 Icaro 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题