• Frugal Cafe
  • Posts
  • FC07 Examine simplest Linq.Enumerable method: Any

FC07 Examine simplest Linq.Enumerable method: Any

Linq Is Not Quick

Now that we’re making the general statement that Linq Is Not Quick, let’s back it up with data. This time let’s check the implementation of the simplest Linq.Enumerable extension method: .Any()

Here is its source code:

So input is already taken as IEnumerable. After null check, enumerator is allocated (always on the heap), then single MoveNext is called.

Let’s write a simple program to test it:

This testing method is designed for us to step into assembly code after warming up. Here we use windbg as debugger, trace using wt command:

Single call is 143 instructions, with an enumerator allocation. So Linq Is Really Not Quick.

Please note that some enumerator implementations could be super costly. One bad example is ConcurrentBag:

ConcurrentBag enumerator is implemented by freeze the whole thing, get a count, copy contents to array, then return the array enumerator. This could cause bad lock contention and large object allocation.

Here is SortedSet enumerator implementation:

It allocates a stack (two allocations), then move to the left-most leave node, so it’s O(Ln(N)).