从编译器的角度来看字符串是怎样的?

How do strings look from the compiler's point of view?

C 中,编译器有一个指向字符串开头的指针和一个结束符号 ('[=11=]')。如果用户想要计算字符串的长度,编译器必须对字符串数组的元素进行计数,直到找到 '[=11=]'.

UCSD-strings中,编译器在第一个符号中有字符串的长度。

编译器对 C#-strings 的看法是什么?是的,从用户的角度来看 String 是一个 object 有一个字段 Length,我不是在谈论高层次的东西。我想了解深度算法;例如,编译器如何计算字符串的长度?

在C#中,字符串的长度存储在对象的私有字段([NonSerialized]private int m_stringLength;)中,不需要在运行时计算。

The source code of String class is available online.

让我们执行以下代码:

string s = "123";
string s2 = "234";
string s3 = s + s2;
string s4 = s2 + s3;
Console.WriteLine(s + s2);

现在我们在最后一行打个断点,打开内存window:

在内存中写入s3window可以看到2个(s3s4)字符串依次分配,大小为4字节开始。

您还可以看到分配了其他内存,例如 strings class 类型令牌和其他 string class 数据。

string class 本身包含一个成员 private int m_stringLength; ,其中包含 string 的长度,这也使得 string.Concat() 执行速度超快(通过将整个长度分配在开头):

int totalLength = str0.Length + str1.Length + str2.Length;

String result = FastAllocateString(totalLength);
FillStringChecked(result, 0, str0);
FillStringChecked(result, str0.Length, str1);
FillStringChecked(result, str0.Length + str1.Length, str2);

我觉得有点奇怪的是 IEnumerable<char>.Count()string 的实现是使用默认实现完成的,这意味着一个一个地迭代项目,不像 ICollection<T>List<T> 其中 IEnumerable<char>.Count() 是通过其 ICollection<T>.Count 属性.

实现的