为什么 C#/.NET 字符串带有长度前缀并以 null 结尾?
阅读空终止字符串的基本原理是什么?和一些类似的问题后我发现在 C#/.NET 字符串内部,长度前缀和 null 终止,就像 BSTR 数据类型。
字符串都带有长度前缀和空终止而不是例如的原因是什么?仅长度前缀?
After reading What's the rationale for null terminated strings? and some similar questions I have found that in C#/.NET strings are, internally, both length-prefixed and null terminated like in BSTR Data Type.
What is the reason strings are both length-prefixed and null terminated instead of eg. only length-prefixed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
长度前缀,以便计算长度为
O(1)
。空终止以使编组到非托管的速度非常快(非托管可能需要空终止字符串)。
Length prefixed so that computing length is
O(1)
.Null terminated to make marshaling to unmanaged blazing fast (unmanaged likely expects null-terminated strings).
以下是 Jon Skeet 的博客 帖子 关于字符串的摘录:
Here is an excerpt from Jon Skeet's Blog Post about strings:
最有可能的是,为了确保与 COM 的轻松互操作性。
Most likely, to ensure easy interoperability with COM.
虽然长度字段使框架可以轻松确定字符串的长度(并且它允许字符串包含零值的字符),但框架(或用户程序)需要处理大量的内容以 NULL 结尾的字符串。
例如,像 Win32 API。
因此,在字符串数据末尾保留 NULL 终止符很方便,因为无论如何它可能需要经常出现。
请注意,C++ 的
std::string
类以相同的方式实现(无论如何在 MSVC 中)。出于同样的原因,我确信(c_str()
通常用于将std::string
传递给需要 C 风格字符串的对象)。While the length field makes it easy for the framework to determine the length of a string (and it lets string contain characters with a zero value), there's an awful lot of stuff that the framework (or user programs) need to deal with that expect NULL terminated strings.
Like the Win32 API, for example.
So it's convenient to keep a NULL terminator on at the end of the string data because it's likely going to need to be there quite often anyway.
Note that C++'s
std::string
class is implemented the same way (in MSVC anyway). For the same reason, I'm sure (c_str()
is often used to pass astd::string
to something that wants a C-style string).最好的猜测是,与遍历长度相比,找到长度是恒定的 (O(1)),运行时间为 O(n)。
Best guess is that finding the length is constant (O(1)) compared to traversing it, running in O(n).