【问题标题】:In the build folder, why is a concat-file smaller then a "+"file? [Java]在 build 文件夹中,为什么 concat 文件比“+”文件小? [爪哇]
【发布时间】:2018-01-18 09:30:29
【问题描述】:

正如标题所述。为什么文件变小了?我知道“+”调用了一个 StringBuilder,但我仍然不明白为什么当最终结果相同时这会导致更多的内存使用。

public class ConcatWithPlus {
    public static void main(String[] s) {
        String www = "www.";
        String company = "nyhetsbolaget.";
        String country = "se";

        System.out.println(www+company+country);

public class ConcatWithConcat {
    public static void main(String[] s) {
        String www = "www.";
        String company = "nyhetsbolaget.";
        String country = "se";

        System.out.println(www.concat(company).concat(country));
    }
}

【问题讨论】:

  • 您使用什么代码创建文件?
  • 欢迎来到 Stack Overflow!请收下tour,环顾四周,并通读help center,尤其是How do I ask a good question?。让您的问题清晰而详细很重要。向我们展示您正在对比的两段代码(理想情况下,作为我们可以编译和比较的完整 Java 文件)。
  • 你一定是做错了什么。我测试了它,两个文件都有 22 个字节
  • 即使在构建文件夹中,文件已被编译?

标签: java concat


【解决方案1】:

当我尝试使用 javac 1.8.0_152 时,ConcatWithConcat.class(568 字节)小于 ConcatWithPlus.class(640 字节)。这是意料之中的,因为表达式 www+company+country 会导致编译器生成与以下内容等效的代码:

StringBuilder __compilerGeneratedName = new StringBuilder();
__compilerGeneratedName
        .append(www)
        .append(company)
        .append(country)
        .toString();

...这比使用 concat 稍微冗长一些,即使最终结果相同。

那么为什么编译器不生成与调用concat() 等效的代码,如果它更小呢? Java API 创建者已经确定使用StringBuilder 更有效(可能是因为调用concat 会导致创建中间字符串)。

【讨论】:

  • 是的,一定是这个!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-02
  • 1970-01-01
相关资源
最近更新 更多