views:

47

answers:

2

How is an arrays Length property identified, by an internal variable (i.e. m_Length) or it's gonna enumerate thru all the items of the array.

The difference takes place if I want to check whether an array contains any elements.

Dim asdf = { "a"c, "s"c, "d"c, "f"c }
Dim any = asdf.Any()
Dim any2 = asdf.Length > 0

(Also note that Any is an extension method, and I want to take into account the performance comparison of calling the internal get_Length vs. calling an ex. method.

+3  A: 

array.Length is a property and an O(1) operation. An array's length is known at the time it is created, so there is no reason to enumerate the entire array when you access the Length property. Any() should be fairly fast, and certainly useful if the collection type could change to be any other IEnumerable<T>, but Length is not going to be performance drag.

Also, your specific example uses a string and not an array, but the message is the same. The length of the string is known at the time of creation, so Length would not need to enumerate the characters in the string when you access the property.

Anthony Pegram
+7  A: 

The asdf variable in your code is not an array, it's a String. It just so happens that String has a Length property and implements IEnumerable<char>, which allows you to call Any().

Nonetheless, to answer your actual question, determining an array's length does not require enumeration; the length is stored as part of the array.

Technically, using Length would be faster than calling Any() (since that has to create an enumerator for the array, then call MoveNext once), though the difference is likely negligible. Checking the Length variable is more in line with convention, though.

Adam Robinson