开发者

How is String.Length implemented in C#?

开发者 https://www.devze.com 2023-03-15 20:26 出处:网络
As per my开发者_JS百科 understanding, there is no null-termination at the end of a C# string. So how does Length get to know how many characters a string have?

As per my开发者_JS百科 understanding, there is no null-termination at the end of a C# string. So how does Length get to know how many characters a string have?

Thanks, Gyan


It's stored in a field within the object.

As it happens, strings are null-terminated internally in the current implementation of .NET, but that's only for the sake of interop, so that code which does expect null-terminated strings can be given the same chunk of memory to work with.

Note that having it in a field is a good idea in terms of performance anyway - it makes finding the length an O(1) operation instead of O(N).

0

精彩评论

暂无评论...
验证码 换一张
取 消