the internals of System.String

前端 未结 4 582
遇见更好的自我
遇见更好的自我 2021-02-13 08:59

I used reflection to look at the internal fields of System.String and I found three fields:

m_arrayLength

m_stringLength

m_firstChar

I don\'t

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 09:39

    The first char provides access (via &m_firstChar) to an address in memory of the first character in the buffer. The length tells it how many characters are in the string, making .Length efficient (better than looking for a nul char). Note that strings can be oversized (especially if created with StringBuilder, and a few other scenarios), so sometimes the actual buffer is actually longer than the string. So it is important to track this. StringBuilder, for example, actually mutates a string within its buffer, so it needs to know how much it can add before having to create a larger buffer (see AppendInPlace, for example).

提交回复
热议问题