In C#
, when calling Count or Length properties, does C#
internally keep track of the count when the collection is updates? Or, does it count the underlining elements every time these properties are called?
I am trying to understand which is the better code of the following two
if(collection.Count > 0)
{
if(collection.Count > 5)
{
// more than 5
} else if(collection.Count > 10 && collection.Count <= 15)
{
// more than 10
} else {
// more than 15
}
}
else
{
// collection is empty
}
Or should I do this instead
var count = collection.Count;
if(count > 0)
{
if(count > 5)
{
// more than 5
} else if(count > 10 && count <= 15)
{
// more than 10
} else {
// more than 15
}
}
else
{
// collection is empty
}
CodePudding user response:
Microsoft states:
Retrieving the value of this property is an O(1) operation.
This means that is is keeping track of it internally and will not iterate to find the count each time.
Setting the dedicated count variable is not needed.