Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic array Any() vs Length

I have a simple array of objects:

Contact[] contacts = _contactService.GetAllContacts();

I want to test if that method returns any contacts. I really like the LINQ syntax for Any() as it highlights what I am trying to achieve:

if(!contacts.Any()) return;

However, is this slower than just testing the length of the array?

if(contacts.Length == 0) return;

Is there any way I can find out what kind of operation Any() performs in this instance without having to go to here to ask? Something like a Profiler, but for in-memory collections?

like image 864
CodingIntrigue Avatar asked Mar 18 '14 08:03

CodingIntrigue


People also ask

How to get length of array in VB?

You can find the size of an array by using the Array. Length property. You can find the length of each dimension of a multidimensional array by using the Array. GetLength method.

What is. length in array?

The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

How do you find the length of an array?

Using sizeof() One way​ to find the length of an array is to divide the size of the array by the size of each element (in bytes).

How do I get the length of an array in C#?

To find the length of an array, use the Array. Length() method.


2 Answers

If you have a array the Length is in a property of the array. When calling Any you are iterate the array to find the first element. Setting up the enumerator is probably more expensive then just reading the Length property.

like image 43
Peter Avatar answered Sep 19 '22 23:09

Peter


There are two Any() methods: 1. An extension method for IEnumerable<T> 2. An extension method for IQueryable<T>

I'm guessing that you're using the extension method for IEnumerable<T>. That one looks like this:

public static bool Any<T>(this IEnumerable<T> enumerable)
{
    foreach (var item in enumerable)
    {
        return true;
    }

    return false;
}

Basically, using Length == 0 is faster because it doesn't involve creating an iterator for the array.

If you want to check out code that isn't yours (that is, code that has already been compiled), like Any<T>, you can use some kind of disassembler. Jetbrains has one for free - http://www.jetbrains.com/decompiler/

like image 72
Shani Elharrar Avatar answered Sep 18 '22 23:09

Shani Elharrar