If strings are immutable in .NET, then why does Substring take O(n) time?

后端 未结 5 1824
醉酒成梦
醉酒成梦 2020-11-28 00:33

Given that strings are immutable in .NET, I\'m wondering why they have been designed such that string.Substring() takes O(substring.Length) time, i

5条回答
  •  眼角桃花
    2020-11-28 01:10

    Java used to reference larger strings, but:

    Java changed its behavior to copying as well, to avoid leaking memory.

    I feel like it can be improved though: why not just do the copying conditionally?

    If the substring is at least half the size of the parent, one can reference the parent. Otherwise one can just make a copy. This avoids leaking a lot of memory while still providing a significant benefit.

提交回复
热议问题