Bas Bas - 29 days ago 10
C# Question

Most efficient way to determine if a list is empty

I have a function which will be called thousands of times per day, and I want to optimize this function so it will be as fast and efficient as possible.

In this function, a list will be checked and based on the result of this check, different actions will happen. My question is what is the most efficient way of determining how many elements are in this list.

Obviously, you can just check like this:

List<Objects> data = GetData();
if (data.Count == 0)
{
//Do something
}
else if (data.Count < 5)
{
//Do something with a small list
}
else
{
//Do something with a larger list
}


Is this already the fastest/most efficient way of doing this?
I came up with an alternative, but I would like some suggestions

List<Objects> data = GetData();
int amountOfObjects = data.Count();
if (amountOfObjects == 0)
{
//Do something
}
else if (amountOfObjects < 5)
{
//Do something with a small list
}
else
{
//Do something with a larger list
}

Answer

You should use the property Count as it is a pre-calculated value and will not require recalculating the value when you use it, whereas the method Count() will try to be a smart ass and try to work out if it needs to recount or not, but that working out alone is still more effort than just using Count.

So just use what you have initially done.