DEV Community

Discussion on: Dear LINQ, I love you, but I'm going back to my roots

Collapse
 
alexfomin profile image
Alex Fomin • Edited

LINQ allows you to focus on what you want to get rather than how you can get this. Compare two pieces of code:

 return items.Where(x => x % Divider == 0).ToList();

and

for (var i = 0; i < items.Count; i++)
{
  if (items[i] % Divider == 0)
  {
    items.RemoveAt(i);
    i--;
  }
}

return items;

It is almost takes nothing to understand first piece of code, while you need to get through five lines to understand second one. And as you have noted, the second one is error prone - do not forget to decrease i and so on.

As for performance and memory pressure, LINQ is far better than your approach. Here is the gist with benchmark:

And results are:

           Method |        Mean |      Error |     StdDev |    Gen 0 |    Gen 1 |   Gen 2 | Allocated |
----------------- |------------:|-----------:|-----------:|---------:|---------:|--------:|----------:|
 FilterEnumerable |    834.1 us |   8.983 us |   7.501 us | 427.7344 | 427.7344 | 71.2891 |  455.1 KB |
       FilterList | 42,794.5 us | 878.850 us | 822.077 us | 375.0000 | 375.0000 | 62.5000 | 390.73 KB |

LINQ is 50 times faster while memory allocation is almost the same. Well, you'll create a new List, right. But complexity of FilterEnumerable is O(N) while FilterList is O(N2).

As any other tool, LINQ is great in right hands. You need to know it pitfalls to use it more efficiently, but LINQ allows you not only write more efficient code, but gives you better tools for decomposition of your code as well.