Time Complexity of ICollection.Count and Array.Length Property

93 Views Asked by At

I was wondering if the ICollection.Count is just a lookup (Time Complexity in O(1)) or iterates over the Collection. Same for the Array.Length property.

Also, if I have the option to use both, which one is better to use?

1

There are 1 best solutions below

1
On BEST ANSWER

Array.Length is a O(1) operation - the length is stored and simply read-n-returned to the user.

ICollection.Count is a member of an interface. Interfaces are contracts and hence do not contain implementations.

So, anyone could write any implementation they want, so the complexity is undefined in a general case.

However, it is strongly implied — by (a) the member Count being a property and by (b) the interface itself being a separate entity from IEnumerable<> — that it should have O(1) complexity as well.