views:

1318

answers:

4

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?

OR

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

+1  A: 

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.

Jeff Ancel
+6  A: 

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.

Noldorin
+6  A: 

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.

driis
+2  A: 

.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.

tylerl
It's not really "pre-calculated" as much as Length property for the immutable String class simply returns the Length property for the underlying data structure.
Babak Naffas
There is actually a number stored there (in the underlying data structure) that represents the length of the string, and the number exists as the result of some calculation. Whether or not you ever use the Length property, that number is always calculated and always stored in the underlying data structure. That's what I mean by "pre-calculated".
tylerl