StringBuilder/StringBuffer 与“+”运算符

2023-11-26

我正在阅读 ”更好、更快、更轻的 Java“(作者 Bruce Tate 和 Justin Gehtland)并且熟悉敏捷类型团队的可读性要求,例如 Robert Martin 在他的干净编码书中讨论的内容。在我现在所在的团队中,我被明确告知不要这样做使用+运算符,因为它在运行时创建额外的(且不必要的)字符串对象。

但是这个article,写在'04年,讲的是对象分配大约是10条机器指令。 (本质上免费)

它还讨论了 GC 如何帮助降低此环境中的成本。

使用之间的实际性能权衡是什么+, StringBuilder or StringBuffer? (就我而言,它是StringBuffer仅因为我们仅限于 Java 1.4.2。)

StringBuffer对我来说,这会导致代码丑陋、可读性较差,正如泰特书中的几个例子所证明的那样。和StringBuffer是线程同步的,这似乎有其自身的成本,超过了使用的“危险”+操作员。

想法/意见?


Using String连接被翻译成StringBuilder编译器的操作。

为了了解编译器的工作原理,我将获取一个示例类,对其进行编译并使用 jad 对其进行反编译,以查看生成的字节码。

原班:

public void method1() {
    System.out.println("The answer is: " + 42);
}

public void method2(int value) {
    System.out.println("The answer is: " + value);
}

public void method3(int value) {
    String a = "The answer is: " + value;
    System.out.println(a + " what is the question ?");
}

反编译后的类:

public void method1()
{
    System.out.println("The answer is: 42");
}

public void method2(int value)
{
    System.out.println((new StringBuilder("The answer is: ")).append(value).toString());
}

public void method3(int value)
{
    String a = (new StringBuilder("The answer is: ")).append(value).toString();
    System.out.println((new StringBuilder(String.valueOf(a))).append(" what is the question ?").toString());
}
  • On method1编译器在编译时执行该操作。
  • On method2 the String串联相当于手动使用StringBuilder.
  • On method3 the String连接肯定是不好的,因为编译器正在创建第二个StringBuilder而不是重复使用前一个。

所以我的简单规则是,除非您需要再次连接结果,否则连接是好的:例如在循环中或当您需要存储中间结果时。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

StringBuilder/StringBuffer 与“+”运算符 的相关文章

随机推荐