是string.length减在C#(.NET)瞬间变?瞬间、string、length、NET

2023-09-03 01:31:54 作者:赤色火焰

我不知道是否 string.length减在C#中是一个即时变量。通过即时变我的意思是,当我创建的字符串:

I'm wondering if string.Length in C# is an instant variable. By instant variable I mean, when I create the string:

string A = "";

A = "Som Boh";

时的长度被计算的呢?

Is length being computed now?

难道只计算后,我试图让则为a.length?

Is it computed only after I try to get A.Length?

推荐答案

首先,请注意,在.NET字符串有很大的不同存储在非托管语言(如C ++)串......在CLR中,的长度串(在字符和字节)是实际上存储在存储器中,使得在CLR知道如何大的存储器包含字符串的块(字符的数组)是。这是在创建的字符串进行,不得到改变并给出了 System.String 类型是不可变的。

Firstly, note that strings in .NET are very different to strings stored in unmanaged languages (such as C++)... In the CLR, the length of the string (in chars and in bytes) is in fact stored in memory so that the CLR knows how large the block of memory (array of chars) containing the string is. This is done upon creation of the string and doesn't get changed given that the System.String type is immutable.

在C ++中,这是相当不同的,作为一个字符串的长度被发现通过读取,直到第一个空字符。因为在CLR的方式内存使用的作品,你基本上可以认为得到一个字符串的长度属性就像检索一个 INT 变量。性能开销这里将是绝对最小的,如果这是你考虑的东西。

In C++ this is rather different, as the length of a string is discovered by reading up until the first null character. Because of the way memory usage works in the CLR, you can essentially consider that getting the Length property of a string is just like retrieving an int variable. The performance cost here is going to be absolutely minimal, if that's what you're considering.

如果你想阅读更多有关.NET中的字符串,尝试在乔恩斯基特的文章话题 - 它似乎拥有所有你可能曾经想知道在.NET中字符串的细节

If you want to read up more about strings in .NET, try Jon Skeet's article on the topic - it seems to have all the details you might ever want to know about strings in .NET.