While reading a recent article in MSDN magazine, I came across some code that gives me a great opportunity to show how to get more done with less effort by using LINQ.
Here’s the code I found, showing how to build three parallel arrays from a List<BugInfo>
:
The first, and obvious, suggestion to make is to use foreach
instead of for
:
While this does incur the overhead of maintaining the index independently, this does avoid indexing into the list multiple times, and I’d suggest this code is easier to read.
The second, and less obvious, suggestion is to use LINQ to generate the arrays directly:
Shorter still - very short, even - and easy to read. More importantly, many fewer opportunities to get it wrong, introducing a bug.
(Before someone flames me with the obvious: Yes, this is (technically) worse performing because it will iterate the list three times - but I’d suggest the difference isn’t likely to be significant. Micro-optimizations are seldom worth the effort. As always, don’t guess at performance, measure it with a profiler.)
Comments
blog comments powered by Disqus