Let’s perform an analysis on different Methods of attaining the maximum value of a list of elements.
One of the limitations that I’ve encountered of the Max LINQ statement is the inability to handle empty sequences. Usually, what I’ve seen is the use of Order By Descending and First Or Default to grab the maximum value of an array. This sorting algorithm approach, while common, is O(n lg n). The Maximum LINQ query, in comparison is O(n).
But are they substantially better when dealing with possible empty sequences?
From the analysis, the OrderByDescending and FirstOrDefault when benchmarked is on average 27us faster on an array of 5000 elements. But what’s fastest is using the Any Clause and null check. At approximately 20 us and 50 us from Order By Descending and Default If Empty method.
What is interesting is the memory allocation of the Maximum and DefaultIfEmpty LINQ is half of the allocation of the OrderByDescending. But DetectIfEmpty method is right in between the two, at 160 B compared to 105 B for the DefaultIfEmpty and 200 B for the OrderByDescending.
While the Algorithmic complexity of the Max is much better than the Sort Algorithm at O(n) vs O(n lg n). The introduction of the DefaultIfEmpty method and the need for a null check in the Max clause, increases the Algorithmic Complexity. We do see a 50% reduction in Allocated Memory. While not the prettiest, evaluating the query and performing a null check and an any clause to grab the maximum value is a lot more time performant than both methods, although not as space efficient.