Home > Net >  Are the Count or Length property computed every time they are called?
Are the Count or Length property computed every time they are called?

Time:08-13

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.

Source: https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.count?redirectedfrom=MSDN&view=net-6.0#remarks

  •  Tags:  
  • c#
  • Related