在Java中计算字符串拼接的操作次数。

huangapple go评论91阅读模式
英文:

Counting Operations of String Concatenation in Java

问题

我正在尝试理解为什么在Java中,字符串拼接的时间复杂度是O(n)
我们被告知 s1 + s2 不仅会创建一个新的字符串,其长度为 s1.length() + s2.length(),还会将 s1s2 复制到这个新字符串中。
因此,他们计算出了以下成本:2 + 2(n+1) + 1 => (5 + 2n)

我不确定我是否理解我的讲师是如何得出这个计算结果的。是否有人介意向我解释一下字符串拼接的操作,以证明上述提到的成本呢?

英文:

I'm trying to understand why String Concatenation is O(n) time complexity in Java.
We were told that s1 + s2 is going to both create a new string with length of s1.length() + s2.length(), and copy s1 and s2 into that new string.
So the following cost was calculated (by them) 2 + 2(n+1) + 1 => (5 + 2n)

I'm not sure I understand how my lecturers got that calculated. Would anyone mind explaining the operations of string concatenation to me that justifies the above mentioned cost?

答案1

得分: 0

以下是翻译好的内容:

我会谨慎地对 Java 中的字符串拼接进行假设,因为从 Java 9 开始,其内部发生了变化。

关于这个主题的一个很好的演示可以在这里找到:https://www.javaspecialists.eu/talks/pdfs/2018%20Voxxed%20in%20Thessaloniki,%20Greece%20-%20%22Enough%20java.lang.String%20to%20Hang%20Ourselves%20...%22%20by%20Heinz%20Kabutz.pdf

另外值得阅读的资源:https://dzone.com/articles/jdk-9jep-280-string-concatenations-will-never-be-t

虽然有点老了,但对你可能仍有参考价值:https://stackoverflow.com/a/15401136/875083

英文:

I would be careful making assumptions regarding what is happening during String concatenation in Java since it changed internally starting with Java 9.

A good presentation regarding this topic can be found here: https://www.javaspecialists.eu/talks/pdfs/2018%20Voxxed%20in%20Thessaloniki,%20Greece%20-%20%22Enough%20java.lang.String%20to%20Hang%20Ourselves%20...%22%20by%20Heinz%20Kabutz.pdf

Also worth reading: https://dzone.com/articles/jdk-9jep-280-string-concatenations-will-never-be-t

And already a bit older but maybe relevant to you: https://stackoverflow.com/a/15401136/875083

huangapple
  • 本文由 发表于 2020年10月21日 15:25:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64458600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定