gpt4 book ai didi

java - 为什么调试String拼接的时候会弹出StringBuilder?

转载 作者:搜寻专家 更新时间:2023-11-01 01:36:30 24 4
gpt4 key购买 nike

我知道 String 是不可变的,以及何时使用 StringBuilder 或 StringBuffer。我还读到这两个片段的字节码最终会相同:

//Snippet 1
String variable = "text";
this.class.getResourceAsStream("string"+variable);

//Snippet 2
StringBuilder sb = new StringBuilder("string");
sb.append("text");
this.class.getResourceAsStream(sb.toString());

但我显然有问题。在 eclipse 中通过代码段 1 进行调试时,我实际上被带到了 StringBuilder 构造函数和 append 方法。我想我缺少有关如何解释字节码以及调试器如何引用源代码中的行的详细信息;如果有人可以解释一下,我将不胜感激。另外,也许您可​​以指出什么是特定于 JVM 的,什么不是(例如,我正在运行 Oracle 的 v6),谢谢!

最佳答案

Why do StringBuilders pop up when debugging String concatenation?

因为字符串连接(通过“+”运算符)通常被编译为使用 StringBufferStringBuilder 进行连接的代码。 JLS 明确允许这种行为。

"An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression." JLS 15.18.1.

(如果您的代码使用的是 StringBuffer 而不是 StringBuilder,这可能是因为它是使用非常古老的 Java 编译器编译的,或者因为您指定了一个非常老的目标 JVM。StringBuilder 类是对 Java 的相对补充。旧版本的 JLS 过去常常提到 StringBuffer 而不是 StringBuilder,IIRC .)


Also, maybe you can point out what's JVM specific and what isn't.

"string"+ variable" 生成的字节码取决于 Java 编译器如何处理连接。(事实上,所有生成的字节码在某种程度上都依赖于 Java 编译器。JLS 和 JVM 规范不要规定必须生成什么字节码。规范更多的是关于程序应该如何表现,以及各个字节码做什么。)


@supercat 评论:

I wonder why string concatenation wouldn't use e.g. a String constructor overload which accepts two String objects, allocates a buffer of the proper combined size, and joins them? Or, when joining more strings, an overload which takes a String[]? Creating a String[] containing references to the strings to be joined should be no more expensive than creating a StringBuilder, and being able to create a perfect-sized backing store in one shot should be an easy performance win.

也许……但我会说可能不会。这是一个涉及复杂权衡的复杂领域。所选的字符串连接实现策略必须适用于各种不同的用例。

我的理解是,最初的策略是在查看了多种方法并进行了一些大规模静态代码分析和基准测试以试图找出最佳方法后选择的。我想象他们考虑了您提出的所有备选方案。 (毕竟,他们曾经/是聪明人……)

话虽如此,您仍可以使用 Java 6、7 和 8 的完整源代码库。这意味着您可以下载它,并自己尝试一些实验,看看您的理论是否正确。如果它们是……并且您可以收集确凿的证据证明它们是……然后向 OpenJDK 团队提交补丁。

关于java - 为什么调试String拼接的时候会弹出StringBuilder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11815255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com