String.Substring (): copy or link?

When a row is created using the SubString () method, is the resulting row a copy of the elements of the original row (so now there are 2 memory cells with the same information) or is it a reference to the existing location memory?

If this is a copy, is there a way to make it a link?

+4
source share
3 answers

In C #, strings are immutable * but not constant. This means that the new line resulting from the SubString method SubString not use the common part with the old line. Here is a great explanation from Eric Lippert.

* operation in a string will return a new string object

+5
source

This is a copy, and you cannot have a string reference to part of another string. The .net string is not supported by the array; it contains an inline char string. those. it is a variable-length class similar to an array.

While this subreference model is a possible implementation (I think java strings are just fragments in char arrays), this can lead to strange behavior when storing a small substring keeps the entire string in memory, a common error with java substrings. I think .net developers wanted to avoid such problems.

You can use your own type string that has this property. For example, you can work with slices into a char array with ArraySegment<char> .

+5
source

This is a new line. You could knock something that says that the position of some other line started and ended, for example, the arguments you sent to a substring if you called it. If it was a fixed template (or at least can be fixed for a known interval, you can crop it beforehand or use StringBuilder or Stream with TextReader.

I would say that if a substring is a problem in a language with immutable strings, you should develop a need for it. It is convenient, but it should be one.

0
source

Source: https://habr.com/ru/post/1394299/


All Articles