Why does .NET create new substrings instead of pointing into existing strings?

后端 未结 5 1276
别跟我提以往
别跟我提以往 2021-01-02 11:35

From a brief look using Reflector, it looks like String.Substring() allocates memory for each substring. Am I correct that this is the case? I thought that woul

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 12:13

    Each string has to have it's own string data, with the way that the String class is implemented.

    You can make your own SubString structure that uses part of a string:

    public struct SubString {
    
       private string _str;
       private int _offset, _len;
    
       public SubString(string str, int offset, int len) {
          _str = str;
          _offset = offset;
          _len = len;
       }
    
       public int Length { get { return _len; } }
    
       public char this[int index] {
          get {
             if (index < 0 || index > len) throw new IndexOutOfRangeException();
             return _str[_offset + index];
          }
       }
    
       public void WriteToStringBuilder(StringBuilder s) {
          s.Write(_str, _offset, _len);
       }
    
       public override string ToString() {
          return _str.Substring(_offset, _len);
       }
    
    }
    

    You can flesh it out with other methods like comparison that is also possible to do without extracting the string.

提交回复
热议问题