3 ms·
In my experience, so much of the problems with Linq are problems with knowing the right data structures for the job, and that's something of a universal problem
by WorldMaker 7y ago
In my experience, so much of the problems with Linq are problems with knowing the right data structures for the job, and that's something of a universal problem, Linq just makes it easier to forget to pay attention to what your data structures are; the same code written equivalently in indexed for loops or foreach loops makes the exact same mistakes. More junior programmers are just at least somewhat more familiar at spotting where they are using the wrong data type in a for loop or foreach, partly because they'd recognize when they have more loops than they expected (.First() when alone is a loop).
I've long joked that ToList() should be considered harmful, because it's an interesting crutch that gets over used and List<T> is so often the wrong data type for the operations to follow. Every time I have stepped in to performance optimize a Linq-heavy codebase, I've started by finding and removing nearly every use of ToList().
ToLookup() is one of the frequently unsung heroes of Linq that gets overlooked too often. It is the "indexing" operator, as ILookup<K, V> is the out-of-the-box multi-value Dictionary of .NET. I think ToLookup() gets overlooked often because there's no concrete, mutable Lookup<K, V> in the BCL (MultiValueDictionary<K, V> exists in the Experimental Collections NuGet package).
Deleting unnecessary ToList()s (where a query was "cut in half", presumably for debug reasons) and then converting nearly every remaining instance of ToList() to ToDictionary() or ToLookup() based on queries/usage patterns that followed was often alone a huge performance boost to Linq code that I found, simply because it was using a more useful data structure. Sometimes you don't even have to do any of the more complicated performance testing/debugging work and can stop there at the easy stuff.