user4189129
user4189129

Reputation:

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
}

Upvotes: 2

Views: 5436

Answers (2)

Georg
Georg

Reputation: 5771

For List<T>, the Count property really just returns a field because the implementation is an array list that needs to know very precisely how many elements are in this collection. Therefore, you won't gain any performance by trying to cache this value or anything alike. This is just no problem.

This situation may be different when you use other collection implementations. For example, a LinkedList conceptually has no clue of how many elements are in it, but has to count them, which is an expensive operation.

Edit: Your alternative using Count() is actually a very bad thing. Since List<T> is sealed, the compiler will create a static method call for accessing the Count property meanwhile Count() results in a cast and a virtual method call over an interface. That makes up much more cost and the JIT-compiler can do less magic such as inlining.

Upvotes: 1

musefan
musefan

Reputation: 48415

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.

Upvotes: 2

Related Questions