the internals of System.String

前端 未结 4 1730
不思量自难忘°
不思量自难忘° 2021-02-13 08:53

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条回答
  •  攒了一身酷
    2021-02-13 09:31

    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).

提交回复
热议问题