Main array Any () vs Length

I have a simple array of objects:

Contact[] contacts = _contactService.GetAllContacts(); 

I want to check if this method returns any contacts. I really like the LINQ syntax for Any() , as it emphasizes what I'm trying to achieve:

 if(!contacts.Any()) return; 

However, is it slower than just checking the length of the array?

 if(contacts.Length == 0) return; 

Is there any way to find out which Any() operation is performed in this case without having to go here? Something like Profiler, but for collections in mind?

+7
c # linq linq-to-objects
source share
5 answers

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

I assume that you are using the extension method for IEnumerable<T> . It looks like this:

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

In principle, using Length == 0 is faster because it is not related to creating an iterator for an array.

If you want to check code that does not belong to you (that is, code that has already been compiled), for example Any<T> , you can use some kind of disassembler. Jetbrains has one for free - http://www.jetbrains.com/decompiler/

+6
source share

If you have an array, the length is in the array property. When you call Any, you iterate over the array to find the first element. Setting up a counter is probably more expensive than just reading the Length property.

+4
source share

Yes, it is slower because it goes through the elements. It is better to use the Length property. But still, I don't think there is a significant difference, because Any returns true as soon as it finds an element.

+3
source share

In your case, Length little better:

  // Just private field test if it zero or not if (contacts.Length == 0) return; // Linq overhead could be added: eg a for loop // for (int i = 0; i < contains.Length; ++i) // return true; // plus inevitable private field test (i < contains.Length) if (!contacts.Any()) return; 

But the difference seems insignificant.

In general, however, Any better because it stops at the first element found

  // Itterates until 1st item is found if (contains.Any(x => MyCondition(x))) return; // Itterates the entire collection if (contains.Select(x => MyCondition(x)).Count() > 0) return; 
+3
source share

I must completely disagree with the other answers. It certainly does not iterate over the array . It will be slightly slower because it needs to create an array iterator object and call MoveNext() once , but this cost should be negligible in most scenarios; if Any() makes the code more readable for you, feel free to use it.

Source: decompiled Enumerable.Any<TSource> code.

+2
source share

All Articles