gpt4 book ai didi

Java 7 String - 子串复杂度

转载 作者:搜寻专家 更新时间:2023-11-01 03:52:33 25 4
gpt4 key购买 nike

在 Java 6 之前,我们在 String 上有一个常量时间子字符串。在 Java 7 中,为什么他们决定继续复制 char 数组 - 并降低到线性时间复杂度 - 而像 StringBuilder 这样的东西正是为此目的?

最佳答案

为什么他们决定在 Oracle bug #4513622 : (str) keeping a substring of a field prevents GC for object 中讨论:

When you call String.substring as in the example, a new character array for storage is not allocated. It uses the character array of the original String. Thus, the character array backing the the original String can not be GC'd until the substring's references can also be GC'd. This is an intentional optimization to prevent excessive allocations when using substring in common scenarios. Unfortunately, the problematic code hits a case where the overhead of the original array is noticeable. It is difficult to optimize for both edges cases. Any optimization for space/size trade-offs are generally complex and can often be platform-specific.

还有这个 note ,注意到根据测试,曾经的优化已经变成了悲观:

For a long time preparations and planing have been underway to remove the offset and count fields from java.lang.String. These two fields enable multiple String instances to share the same backing character buffer. Shared character buffers were an important optimization for old benchmarks but with current real world code and benchmarks it's actually better to not share backing buffers. Shared char array backing buffers only "win" with very heavy use of String.substring. The negatively impacted situations can include parsers and compilers however current testing shows that overall this change is beneficial.

关于Java 7 String - 子串复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21463910/

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