Is string.Length in C# (.NET) instant variable?

前端 未结 4 1095
陌清茗
陌清茗 2020-12-11 16:24

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          


        
相关标签:
4条回答
  • 2020-12-11 16:40

    It looks like it is a property of string, which is probably set in the constructor. Since it is not a function, I doubt that it is computed when you call it. They are simply getting the value of the Length property.

    0 讨论(0)
  • 2020-12-11 16:42

    .NET strings are stored with the length pre-computed and stored at the start of the internal structure, so the .Length property simply fetches that value, making it an O(1) function.

    0 讨论(0)
  • 2020-12-11 16:53

    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.

    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.

    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.

    0 讨论(0)
  • 2020-12-11 17:05

    The length of the string is not computed, it is known at construction time. Since String is immutable, there will be no need for calculating it later.

    A .NET string is stored as a field containing the count of characters, and a corresponding series of unicode characters.

    0 讨论(0)
提交回复
热议问题