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

后端 未结 5 1836
醉酒成梦
醉酒成梦 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:14

    Java (as opposed to .NET) provides two ways of doing Substring(), you can consider whether you want to keep just a reference or copy a whole substring to a new memory location.

    The simple .substring(...) shares the internally used char array with the original String object, which you then with new String(...) can copy to a new array, if needed (to avoid hindering garbage collection of the original one).

    I think this kind of flexibility is a best option for a developer.

提交回复
热议问题